Breadth-First Search

Breadth-First Search (BFS) is a graph traversal algorithm that explores all vertices at the current depth level before moving to vertices at the next depth level. It uses a queue data structure and is useful for finding shortest paths in unweighted graphs.

Breadth-First Search Visualization

Complexity

Time Complexity: O(V + E)
Space Complexity: O(V)

Pseudocode

function BFS(graph, start):
  queue = [start]
  visited = {start}
  
  while queue is not empty:
    current = queue.dequeue()
    
    for each neighbor in graph[current]:
      if neighbor not in visited:
        visited.add(neighbor)
        queue.enqueue(neighbor)