Breadth-first search (BFS) Description: • • • • • BFS starts visiting vertices of a graph at an arbitrary vertex by marking it as visited. It visits graph’s vertices by across to all the neighbors of the last visited vertex Instead of a stack, BFS uses a queue Similar to level-by-level tree traversal “Redraws” graph in tree-like fashion (with tree edges and cross edges for undirected graph) Algorithm: ALGORITHM BFS (G) //implements BFS traversal of a given graph //i/p: Graph G = { V, E} //o/p: BFS tree/forest Mark each vertex in V with 0 as a mark of being “unvisited” count 0 for each vertex v in V do if v is marked with 0 bfs(v) bfs(v) count count + 1 mark v with count and initialize a queue with v while the queue is NOT empty do for each vertex w in V adjacent to front’s vertex v do if w is marked with 0 count count + 1 mark w with count add w to the queue remove vertex v from the front of the queue Example: Starting at vertex A traverse the following graph using BFS traversal method: A B C D E F G H Solution: Step Graph Remarks Insert A into queue 1 A A(1) 2 A Insert B, E into queue B A(1), B (2), E(3) B (2), E(3) E 3 4 A B E F Insert F, G into queue G NO unvisited adjacent vertex for E, backtrack B(2), E(3), F(3), G(4) E(3), F(3), G(4) Delete E from queue F(3), G(4) 5 NO unvisited adjacent vertex for F, backtrack Delete F from queue G(4) 6 A B C E F G A B C Insert C, H into queue H G(4), C(5), H(6) C(5), H(6) 7 8 G F E D Insert D into queue H C(5), H(6), D(7) H(6), D(7) NO unvisited adjacent vertex for H, backtrack Delete H from queue D(7) 9 NO unvisited adjacent vertex for D, backtrack Delete D from queue Queue becomes empty. Algorithm stops as all the nodes in the given graph are visited The BFS tree is as follows: (dotted lines are cross edges) A B E G F C H D Applications of BFS: • To check connectivity of a graph (number of times queue becomes empty tells the number of components in the graph) • • To check if a graph is acyclic. (no cross edges indicates no cycle) To find minimum edge path in a graph Efficiency: • Depends on the graph representation: o Array : Θ(n2) o List: Θ(n + e) Difference between DFS & BFS: DFS Data structure Stack No. of vertex orderings 2 orderings Edge types Tree edge Back edge Applications Connectivity Acyclicity Articulation points Efficiency for Θ(n2) adjacency matrix Efficiency for Θ(n + e) adjacency lists BFS Queue 1 ordering Tree edge Cross edge Connectivity Acyclicity Minimum edge paths Θ(n2) Θ(n + e)