Basics-Wrapup

View on GitHub

Breadth-First Search

Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration.

Breadth-First-Search

As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and G lastly to D. It employs the following rules.

Step Traversal Description
1 bfs_one Initialize the queue.
2 bfs_tow We start from visiting S (starting node), and mark it as visited.
3 bfs_three We then see an unvisited adjacent node from S. In this example, we have three nodes but alphabetically we choose A, mark it as visited and enqueue it.
4 bfs_four Next, the unvisited adjacent node from S is B. We mark it as visited and enqueue it.
5 bfs_five Next, the unvisited adjacent node from S is C. We mark it as visited and enqueue it.
6 bfs_six Now, S is left with no unvisited adjacent nodes. So, we dequeue and find A.
7 bfs_seven From A we have D as unvisited adjacent node. We mark it as visited and enqueue it.

At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm we keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied, the program is over.

the only difference i noticed between DFS & BFS is that