Given an adjacency list representation of a directed graph, the task is to find the path from source to every other node in the graph using BFS.
Input: Output: 0 <- 2 1 <- 0 <- 2 2 3 <- 1 <- 0 <- 2 4 <- 5 <- 2 5 <- 2 6 <- 2
Approach: In the images shown below:
- que array stores the vertices reached and we will enqueue a vertex only if it has not been visited and dequeue it once all its child node have been considered.
- In order to distinguish whether the node has been visited or not we will put 1 in visited array at the respective index to signify it has been visited and if at given index 0 is present it will signify that it has not been visited.
- Parent array is to store the parent node of each vertex. For ex. In case of 0 connected to 2, 2 will be the parent node of 0 and we will put 2 at the index 0 in the parent array.
Below is the implementation of the above approach:
0 <- 2 1 <- 0 <- 2 2 3 <- 1 <- 0 <- 2 4 <- 5 <- 2 5 <- 2 6 <- 2
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if incoming edges in a vertex of directed graph is equal to vertex itself or not
- Check if vertex X lies in subgraph of vertex Y for the given Graph
- Check if every vertex triplet in graph contains two vertices connected to third vertex
- Finding minimum vertex cover size of a graph using binary search
- Java Program for Finding the vertex, focus and directrix of a parabola
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
- Maximum difference of count of black and white vertices in a path containing vertex V
- Sum of Nodes and respective Neighbors on the path from root to a vertex V
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Building an undirected graph and finding shortest path using Dictionaries in Python
- Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
- Print all paths from a given source to a destination using BFS
- Traversing directory in Java using BFS
- BFS using STL for competitive coding
- Water Jug problem using BFS
- Diameter of n-ary tree using BFS
- Level of Each node in a Tree from source node (using BFS)
- Count the number of nodes at given level in a tree using BFS.
- BFS using vectors & queue as per the algorithm of CLRS
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Improved By : rituraj_jain