110 likes | 266 Views
Discussion #31 Adjacency Lists; Breadth-First Search & Depth-First Search. Topics. Adjacency list representation Breadth-First Search (BFS) Depth-First Search (DFS). b. c. a. a. a. b. c. b. c. c. b. Simple Notation. Adjacency Lists. For directed graphs:. a. b. c. a. 1. 1.
E N D
Discussion #31Adjacency Lists;Breadth-First Search &Depth-First Search
Topics • Adjacency list representation • Breadth-First Search (BFS) • Depth-First Search (DFS)
b c a a a b c b c c b Simple Notation Adjacency Lists For directed graphs: a b c a 1 1 1 b 0 0 1 { (a,a), (a,b), (a,c), (b,c), (c,b) } c 0 1 0
b 1 c a 3 5 7 Adjacency Lists for Undirected and Weighted Graphs • Undirected Graphs: Make each edge (except loops) go both ways. • Weighted Graphs: • add additional field to node • node-weight pairs
Undirected edges: each edge twice b d c a n nodes = O(n+2m) = O(m) if m>>n O(n) O(m) ~ 2m edges BFS Algorithm queue: a b c d
b d a c = O(n+2m) = O(m) if m>>n n nodes O(n) O(m) ~ 2m edges DFS Algorithm stack: c a b d
a b e c f d BFS Order: a b c e d f BFS vs. DFS BFS Queue a b c e d f Done!
d a f c b e BFS Queue a b c e d f Done! DFS Order: a b c f d e BFS Order: a b c e d f BFS vs. DFS DFS Stack Done! pop a b pop pop c pop f pop d e pop
a a b b c c d d e e f f g g h h i i j j k k m m n n l l BFS & DFS with Directed Graphs DFS BFS a,b,e,j,f,k,l,h,c,g,d,i,m,n Not same as before a,b,c,d,e,f,g,h,i,j,k,l,m,n Same as before, by chance