Lecture 10 - Breadth First Search (BFS) Sanjoy Dasgupta Russell Impagliazzo Ragesh Jaiswal CSE101, Spring 2020, Week-03
Paths in graphs The classic 15-puzzle explore(G,a): a b c d e Graph G = (V,E) V = {configurations of puzzle} f h E: edges between neighboring configurations f b g a i e j Finds a path from a to i. d c i But this isn’t the shortest possible path! h
Distances in graphs Distance between two nodes Physical model: = length of shortest path between them Vertex – ping-pong ball Edge – piece of string f b g a a distance 0 e j d c i h d c b distance 1 dist(a,e) = ? dist(d,g) = ? e f distance 2 Suppose we want to compute distances from some starting node s to all other nodes in G. h i Strategy: layer-by-layer distance 3 first, nodes at distance 0 then, nodes at distance 1 then, nodes at distance 2, etc.
Breadth-first search procedure bfs(G,s) input: graph G = (V,E); node s in V output: for each node u, dist[u] is Suppose we have seen all nodes at set to its distance from s distance · d. How to get the next layer? for u in V: Solution: dist[u] = 1 A node is at distance d+1 if: dist[s] = 0 it is adjacent to some node at Q = [s] // queue containing just s distance d it hasn’t been seen yet while Q is not empty: u = eject(Q) for each edge (u,v) in E: if dist[v] = 1 : inject(Q,v) dist[v] = dist[u]+1
BFS example Distances procedure bfs(G,s) Queue a b c d e f for u in V: [a] 0 1 1 1 1 1 dist[u] = 1 prev[u] = nil [bcd] 0 1 1 1 1 1 dist[s] = 0 [cd] 0 1 1 1 1 1 Q = [s] // queue containing just s while Q is not empty: [de] 0 1 1 1 2 1 u = eject(Q) [e] 0 1 1 1 2 1 for each edge (u,v) in E: if dist[v] = 1 : [f] 0 1 1 1 2 3 inject(Q,v) [] 0 1 1 1 2 3 dist[v] = dist[u]+1 prev[v] = u a b f a b f d c e d c e Shortest path tree
Why does BFS work? procedure bfs(G,s) for u in V: dist[u] = 1 dist[s] = 0 Q = [s] while Q is not empty: u = eject(Q) for each edge (u,v) in E: if dist[v] = 1 : inject(Q,v) dist[v] = dist[u]+1 Claim For any distance d = 0,1,2,..., there is a point in time at which: all nodes at distance · d have their (i) dist[] values correctly set (ii) all other nodes have dist[] = 1 (iii) the queue Q contains exactly the nodes at distance d Running time: O(V + E), like DFS
Two search strategies a b f d c e Depth-first Breadth-first a b f a b f d c e d c e
Edge lengths BFS treats all edges as having the same length. This is rarely true in applications. Denote the length of edge e = (u,v) by l(e) or l e or l(u,v)
Recommend
More recommend