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,
- Breadth First Search or BFS for a Graph
- Implementing Water Supply Problem using Breadth First Search
- Applications of Breadth First Traversal
- Percentage increase in the volume of cuboid if length, breadth and height are increased by fixed percentages
- Reversing a Queue using another Queue
- Best First Search (Informed Search)
- Meta Binary Search | One-Sided Binary Search
- Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
- Reverse tree path using Queue
- Find the arrangement of queue at given time
- Priority Queue of Vectors in C++ STL with Examples
- Right view of Binary Tree using Queue
- BFS using vectors & queue as per the algorithm of CLRS
- Huffman Coding using Priority Queue
- Implementation of Non-Preemptive Shortest Job First 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.