Skip to main content

Breadth-First Search

Breadth-First Search (BFS) is a fundamental graph traversal algorithm used to explore nodes and edges of a graph level by level. Starting from a source node, BFS explores all the neighboring nodes at the present depth before moving on to nodes at the next depth level.

  1. Start at the root node (or any arbitrary node).
  2. Mark the starting node as visited and enqueue it.
  3. While the queue is not empty:
    • Dequeue a node from the front of the queue.
    • If the node has any unvisited adjacent nodes:
      • Mark the adjacent node as visited.
      • Enqueue the adjacent node.
  4. Repeat the process until the queue is empty.

3. How Does Breadth-First Search Work?​

  • BFS explores nodes level by level, ensuring that all nodes at the current level are explored before moving on to the next level.

4. Problem Description​

Given a graph, BFS aims to traverse the graph, visiting all the vertices and edges exactly once in a breadthward motion.

5. Examples​

Example graph:

      0 - 1 - 2
| | |
3 - 4 - 5

6. Constraints​

  • The graph can be directed or undirected.
  • The graph may contain cycles.

7. Implementation​

Breadth-First Search​

from collections import deque

def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)

while queue:
vertex = queue.popleft()
print(vertex, end=" ")

for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)

graph = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4],
4: [1, 3, 5],
5: [2, 4]
}

bfs(graph, 0)

8. Complexity Analysis​

  • Time Complexity: O(V+E)O(V + E) where VV is the number of vertices and EE is the number of edges.
  • Space Complexity: O(V)O(V) due to the queue and visited set.

9. Advantages and Disadvantages​

Advantages:​

  • Guarantees finding the shortest path in unweighted graphs.
  • Simple and easy to implement.

Disadvantages:​

  • Requires more memory compared to DFS due to the queue.
  • May be slower than DFS for deep and densely connected graphs.

10. References​