Download presentation
Presentation is loading. Please wait.
Published bySabina Atkinson Modified over 9 years ago
1
Adjacency Lists; Breadth-First Search & Depth-First Search
2
Adjacency Lists For directed graphs: b a c 1 a123 2 b3 3 c2 bc cb cbaa Simple Notation { (a,a), (a,b), (a,c), (b,c), (c,b) } 010 c 100 b 111 a cba
3
Space: Adjacency Lists vs. Matricies Space (n vertices and m edges) –matrix: n 2 + n (vertex-name size) = matrix size + header size matrix can be bits, but bits are not directly addressable –list: n (header-node size) + m (list-node size) Sparse: few edges 0 in the extreme case –Matrix fixed size: so no size benefit –List variable size: as little as n (vertex-node size) Dense: many edges n 2 in the extreme case –Matrix fixed size: so no size loss –List variable size: as much as n (header-node size) + n 2 (list-node size)
4
Operations: Adjacency Lists vs. Matricies Operations depend on sparse/dense and what’s being done. Examples (n nodes and m edges) –Is there an arc from x to y? Matrix: O(1) check value at (x, y) List: O(n) index to x, traverse list to y or end –Get successor nodes of a node. Matrix: O(n) scan a row List: O(n) traverse a linked list –Get predecessor nodes of a node. Matrix: O(n) scan a column List: O(n+m) traverse all linked lists, which could be as bad as O(n+n 2 ) = O(n 2 ).
5
Adjacency Lists for Undirected and Weighted Graphs Undirected Graphs: aabc bac cab Make each edge (except loops) go both ways. b a c 5 3 7 1 Weighted Graphs: a(a,1)(b,5)(c,3) b(a,5)(c,7) c(a,3)(b,7) - add additional field to node - node-weight pairs
6
Breadth-First Search (BFS)
7
BFS Algorithm Search order: b c d a a b c d = O(n+2m) = O(m) if m>>n Undirected edges: each edge twice Mark start node and enqueue While queue is not empty Dequeue N For each neighbor X of N If X is not marked Mark X and enqueue MarkedNQueue a-a a- bab cab c bc c- dcd d-
8
Depth-First Search (DFS)
9
DFS Algorithm = O(n+2m) = O(m) if m>>n b c d a a b c d DFS (start node) Proc DFS (N) Mark N For each neighbor X of N If X is not marked DFS (X) MarkedNDFS aa abb bcc cdd c b a Search order:
10
BFS vs. DFS ab ec f d MarkedNQueue a-a a- bab cab c eab c e bc e dbc e d ce d fce d f ed f df f- BFS Order: a b c e d f
11
BFS vs. DFS (BFS Order: a b c e d f) ab ec f d MarkedNDFS aa abb bcc cff c bdd b aee a DFS Order: a b c f d e
12
a bcd efghi jk l mn BFS & DFS with Directed Graphs BFS DFS a bcd efghi jk l mn a,b,c,d,e,f,g,h,i,j,k,l,m,n Same as before, by chance a,b,e,j,f,k,l,h,c,g,d,i,m,n Not same as before
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.