BreadthFirst Search BFS Can be used to attempt
Breadth-First Search
BFS • Can be used to attempt to visit all nodes of a graph in a systematic manner • Works with directed and undirected graphs • Works with weighted and unweighted graphs Process: 1 Start with initial node. insert that node in queue. 2 Pick the node from the queue. visit all its successors and insert them into queue. When all successors are visited and enquired the node is said to be visited and add it to output sequence. 3 Repeat step 2 until the queue is empty.
Walk-Through E C B A D H G F Q : EMPTY Nodes visited (output seq. ): EMPTY
Walk-Through Enqueued Array E C B Q EMPTY A D H G F Step 1. Initially Enqueue D. (consider D as staring node) Q D Nodes visited: Empty
Walk-Through Enqueued Array E C B Q : D A D H G F Dequeue D. Visit(D) all its successors). Enqueue unenqueued node adjacent to D Q : C , E , F Nodes visited: D
Walk-Through Enqueued Array E C B Q : C, E , F A D H G F Dequeue C. Visit C. Enqueue unenqueued nodes adjacent to C. (Note: if no node adjacent to it then don’t worry go ahead. Q : E , F Nodes visited: D, C
Walk-Through Enqueued Array E C B Q : E, F A D H G F Dequeue E. Visit E. Enqueue unenqueued nodes adjacent to E. (here C is adjacent to E but it is visited so do not enqueue) Q : F Nodes visited: D, C, E
Walk-Through Enqueued Array E C B Q : F A D H G F Dequeue F. Visit F. Enqueue unenqueued nodes adjacent to F. Q : G Nodes visited: D, C, E, F
Walk-Through Enqueued Array E C B Q : G A D H G F Dequeue G. Visit G. Enqueue unenqueued nodes adjacent to G here it is H only. Q : H Nodes visited: D, C, E, F, G
Walk-Through Enqueued Array E C B Q : H A D H G F Dequeue H. Visit H. Enqueue unenqueued nodes adjacent to H. Q : A , B Nodes visited: D, C, E, F, G, H
Walk-Through Enqueued Array E C B Q : A, B A D H G F Dequeue A. Visit A. Enqueue unenqueued nodes adjacent to A. (Note: if no node adjacent to it then don’t worry go ahead. . ) Q : A Nodes visited: D, C, E, F, G, H, A
Walk-Through Enqueued Array E C B Q : -> B A D H G F Dequeue B. Visit B. Enqueue unenqueued nodes adjacent to B here A is adjacent to B but it is visited so do not enqueue). Q : -> empty Nodes visited: D, C, E, F, G, H, A, B
Walk-Through E C B A D H G F Q empty. Algorithm done. Nodes visited: D, C, E, F, G, H, A, B
- Slides: 13