Breadth First Search or BFS for a Graph in Python (original) (raw)

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.

**Input: adj = [[2,3,1], [0], [0,4], [0], [2]]
**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, 4

**Input: adj = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]
**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, 4

**Input: 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.

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.

**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)