Breadth First Search without using Queue
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,
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V)