Breadth First Search (BFS) is a graph traversal algorithm that starts from a source node and explores the graph level by level. First, it visits all nodes directly adjacent to the source. Then, it moves on to visit the adjacent nodes of those nodes, and this process continues until all reachable nodes are visited.
BFS is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level.
The algorithm starts from a given source vertex and explores all vertices reachable from that source, visiting nodes in increasing order of their distance from the source, level by level using a queue. Since graphs may contain cycles, a vertex could be visited multiple times. To prevent revisiting a vertex, a visited array is used.
Let us understand the working of Breadth First Search with the help of the following Illustration:
Output
0 1 2 3 4
Time Complexity: O(V + E), BFS explores all the vertices and edges in the graph. It visits every vertex and edge only once. Auxiliary Space: O(V), Using a queue to keep track of the vertices that need to be visited.
BFS of a Disconnected Undirected Graph:
In a disconnected graph, some vertices may not be reachable from a single source. To ensure all vertices are visited in BFS traversal, we iterate through each vertex, and if any vertex is unvisited, we perform a BFS starting from that vertex being the source. This way, BFS explores every connected component of the graph.
Output
0 2 3 1 4 5
Time Complexity: O(V + E), The for loop ensures BFS starts from every unvisited vertex to cover all components, but the visited array ensures each vertex and edge is processed only once, keeping the total time complexity to be linear.
Auxiliary Space: O(V), using a queue to keep track of the vertices that need to be visited.
Applications of BFS in Graphs
BFS has various applications in graph theory and computer science, including:
Shortest Path Finding
Cycle Detection
Connected Components
Network Routing
To read more about applications of BFS, read this article.