In BFS, we start with a node. 1) Create a queue and enqueue source into it. Mark source as visited. 2) While queue is not empty, do following a) Dequeue a vertex from queue. Let this be f. b) Print f c) Enqueue all not yet visited adjacent of f and mark them visited.
Below is an example BFS starting from source vertex 1. Note that there can be multple BFSs possible for a graph (even from a particular vertex).
The code here is simplified such that it could be used in competitive coding.
Input: 8 10 0 1 0 2 0 3 0 4 1 5 2 5 3 6 4 6 5 7 6 7 Output: 0 1 2 3 4 5 6 7
This article is contributed by Nikhil Mahendran. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
- Competitive Coding Setup for C++ and Python in VS Code using Python Script
- Python Tricks for Competitive Coding
- Why is python best suited for Competitive Coding?
- What coding habits improve timing in coding contest?
- Geeks Coding Challenge [GCC 2019] - A Three Day Coding Challenge By GeeksforGeeks
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
- 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
- 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
- Detect cycle in an undirected graph using BFS
- Detect Cycle in a Directed Graph using BFS
- Finding the path from one vertex to rest using BFS
- Islands in a graph using BFS