Skip to main content

Breadth First Search (BFS) (Geeks for Geeks)

1. What is Breadth First Search (BFS)?​

Breadth First Search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree's root (or an arbitrary node in the graph) and explores the neighbor nodes at the present depth prior to moving on to nodes at the next depth level.

2. Algorithm for Breadth First Search (BFS)​

  1. Initialize a queue and enqueue the starting node.
  2. Mark the starting node as visited.
  3. While the queue is not empty:
    • Dequeue a node from the queue.
    • Process the dequeued node (e.g., print its value).
    • Enqueue all unvisited adjacent nodes of the dequeued node.
    • Mark the newly enqueued nodes as visited.

3. How does Breadth First Search (BFS) work?​

  • BFS explores all nodes at the present depth level before moving on to nodes at the next depth level.
  • It uses a queue data structure to keep track of nodes to be explored.
  • Nodes are marked as visited to prevent reprocessing.

4. Problem Description​

Given a graph represented as an adjacency list, implement the Breadth First Search (BFS) algorithm to traverse the graph starting from a given source node.

5. Examples​

Example 1:

Input:
graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
start_node = 2
Output: 2 0 3 1

Example 2:

Input:
graph = {
0: [1, 3],
1: [0, 2],
2: [1, 3],
3: [0, 2]
}
start_node = 0
Output: 0 1 3 2

6. Constraints​

  • Thegraphcanhaveanynumberofnodes.The graph can have any number of nodes.
  • Thegraphcanbedirectedorundirected.The graph can be directed or undirected.

7. Implementation​

Written by @ngmuraqrdd
from collections import deque

def bfs(graph, start_node):
visited = set()
queue = deque([start_node])
result = []

while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
result.append(node)
queue.extend(neighbor for neighbor in graph[node] if neighbor not in visited)
return result

# Example usage:
graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
start_node = 2
print(bfs(graph, start_node))

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. Each vertex and edge is processed once.
  • Space Complexity: O(V)O(V), where VV is the number of vertices. This is for the queue and the visited set.

9. Advantages and Disadvantages​

Advantages:

  • Finds the shortest path in unweighted graphs.
  • Simple and easy to understand and implement.

Disadvantages:

  • Can be memory intensive as it stores all vertices in the queue.

10. References​