![]() |
VOOZH | about |
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent nodes. Once all adjacent are visited, then their adjacent are traversed.
Examples:
Input: adj = [[2,3,1], [0], [0,4], [0], [2]]
π Image
Output: [0, 2, 3, 1, 4]
Explanation: Starting from 0, the BFS traversal will follow these steps:
Visit 0 β Output: 0
Visit 2 (first neighbor of 0) β Output: 0, 2
Visit 3 (next neighbor of 0) β Output: 0, 2, 3
Visit 1 (next neighbor of 0) β Output: 0, 2, 3,
Visit 4 (neighbor of 2) β Final Output: 0, 2, 3, 1, 4Input: adj = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]
π Image
Output: [0, 1, 2, 3, 4]
Explanation: Starting from 0, the BFS traversal proceeds as follows:
Visit 0 β Output: 0
Visit 1 (the first neighbor of 0) β Output: 0, 1
Visit 2 (the next neighbor of 0) β Output: 0, 1, 2
Visit 3 (the first neighbor of 2 that hasnβt been visited yet) β Output: 0, 1, 2, 3
Visit 4 (the next neighbor of 2) β Final Output: 0, 1, 2, 3, 4Input: adj = [[1], [0, 2, 3], [1], [1, 4], [3]]
Output: [0, 1, 2, 3, 4]
Explanation: Starting the BFS from vertex 0:
Visit vertex 0 β Output: [0]
Visit vertex 1 (first neighbor of 0) β Output: [0, 1]
Visit vertex 2 (first unvisited neighbor of 1) β Output: [0, 1, 2]
Visit vertex 3 (next neighbor of 1) β Output: [0, 1, 2, 3]
Visit vertex 4 (neighbor of 3) β Final Output: [0, 1, 2, 3, 4]
The algorithm starts from a given source and explores all reachable vertices from the given source. It is similar to the Breadth-First Traversal of a tree. Like tree, we begin with the given source (in tree, we begin with root) and traverse vertices level by level using a queue data structure. The only catch here is that, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a Boolean visited array.
Follow the below given approach:
Following are the implementations of simple Breadth First Traversal from a given source. The implementation uses adjacency list representation of graphs. STL\'s list container is used to store lists of adjacent nodes and a queue of nodes needed for BFS traversal.
Following is Breadth First Traversal (starting from vertex 2) 2 0 3 1
Time Complexity : O(V+E), where V is the number of vertices in graph and E is the number of edges
Auxiliary Space: O(V)
Please refer complete article on Breadth First Search or BFS for a Graph for more details!