Graph Traversal AlgorithmIn this part of the tutorial we will discuss the techniques by using which, we can traverse all the vertices of the graph. Traversing the graph means examining all the nodes and vertices of the graph. There are two standard methods by using which, we can traverse the graphs. Lets discuss each one of them in detail.
Breadth First Search (BFS) AlgorithmBreadth first search is a graph traversal algorithm that starts traversing the graph from root node and explores all the neighbouring nodes. Then, it selects the nearest node and explore all the unexplored nodes. The algorithm follows the same process for each of the nearest node until it finds the goal. The algorithm of breadth first search is given below. The algorithm starts with examining the node A and all of its neighbours. In the next step, the neighbours of the nearest node of A are explored and process continues in the further steps. The algorithm explores all neighbours of all the nodes and ensures that each node is visited exactly once and no node is visited twice. Algorithm
ExampleConsider the graph G shown in the following image, calculate the minimum path p from node A to node E. Given that each edge has a length of 1. Solution:Minimum Path P can be found by applying breadth first search algorithm that will begin at node A and will end at E. the algorithm uses two queues, namely QUEUE1 and QUEUE2. QUEUE1 holds all the nodes that are to be processed while QUEUE2 holds all the nodes that are processed and deleted from QUEUE1. Lets start examining the graph from Node A. 1. Add A to QUEUE1 and NULL to QUEUE2. 2. Delete the Node A from QUEUE1 and insert all its neighbours. Insert Node A into QUEUE2 3. Delete the node B from QUEUE1 and insert all its neighbours. Insert node B into QUEUE2. 4. Delete the node D from QUEUE1 and insert all its neighbours. Since F is the only neighbour of it which has been inserted, we will not insert it again. Insert node D into QUEUE2. 5. Delete the node C from QUEUE1 and insert all its neighbours. Add node C to QUEUE2. 6. Remove F from QUEUE1 and add all its neighbours. Since all of its neighbours has already been added, we will not add them again. Add node F to QUEUE2. 7. Remove E from QUEUE1, all of E's neighbours has already been added to QUEUE1 therefore we will not add them again. All the nodes are visited and the target node i.e. E is encountered into QUEUE2. Now, backtrack from E to A, using the nodes available in QUEUE2. The minimum path will be A → B → C → E.
Next TopicDFS Algorithm
