Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest BFS traversal of the graph starting from 1.
Note: The vertices are numbered from 1 to N.
Input: N = 5, M = 5 Edges: 1 4 3 4 5 4 3 2 1 5 Output: 1 4 3 2 5 Start from 1, go to 4, then to 3 and then to 2 and to 5. Input: N = 3, M = 2 Edges: 1 2 1 3 Output: 1 2 3
Approach: Instead of doing a normal BFS traversal on the graph, we can use a priority queue(min heap) instead of a simple queue. When a node is visited add its adjacent nodes into the priority queue. Every time, we visit a new node, it will be the one with the smallest index in the priority queue. Print the nodes when every time we visit them starting from 1.
Below is the implementation of the above approach:
1 4 3 2 5
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.
- Print the lexicographically smallest DFS of the graph starting from 1
- Breadth First Search or BFS for a Graph
- Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- BFS for Disconnected Graph
- Detect cycle in an undirected graph using BFS
- Detect Cycle in a Directed Graph using BFS
- Islands in a graph using BFS
- Print all paths from a given source to a destination using BFS
- Program to print all the non-reachable nodes | Using BFS
- Lexicographically Smallest Topological Ordering
- BFS vs DFS for Binary Tree
- 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
- Finding the path from one vertex to rest using BFS
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.