Output: BFS traversal = 2, 0, 3, 1
In the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. Therefore, a Breadth-First Traversal of the following graph is 2, 0, 3, 1.
Approach: This problem can be solved using simple breadth-first traversal from a given source. The implementation uses adjacency list representation of graphs.
- STL Vector container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal.
- A DP array is used to store the distance of the nodes from the source. Every time we move from a node to another node, the distance increases by 1. If the distance to reach the nodes becomes smaller than the previous distance, we update the value stored in the DP[node].
Below is the implementation of the above approach:
2, 0, 3, 1,
- Implementing Water Supply Problem using Breadth First Search
- Breadth First Search or BFS for a Graph
- Applications of Breadth First Traversal
- Reversing a Queue using another Queue
- Percentage increase in the volume of cuboid if length, breadth and height are increased by fixed percentages
- Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
- Best First Search (Informed Search)
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Implementation of Non-Preemptive Shortest Job First using Priority Queue
- Postorder traversal of Binary Tree without recursion and without stack
- Inorder Tree Traversal without recursion and without stack!
- Meta Binary Search | One-Sided Binary Search
- Applications of Depth First Search
- Depth First Search or DFS for a Graph
- Top 10 Interview Questions on Depth First Search (DFS)
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- BFS using vectors & queue as per the algorithm of CLRS
- Level order traversal in spiral form | Using one stack and one queue
- Minimum Spanning Tree using Priority Queue and Array List
- Huffman Coding using Priority Queue
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.