ABSTRACT

Breadth-First Search (BFS) is the primary algorithm for finding the shortest path in an unweighted graph. It explores a graph layer-by-layer, ensuring that it visits every node at distance before moving on to any node at distance .


1. The Core Logic: Layer-by-Layer Exploration

The intuition behind BFS is similar to a ripple in a pond. Starting from a source node, the search expands outward in concentric circles:

  1. Level 0: The starting node .
  2. Level 1: All immediate neighbors of .
  3. Level 2: All neighbors of Level 1 nodes that haven’t been visited yet.

2. Implementation with a Queue

To maintain this specific “level-by-level” order, BFS uses a Queue (First-In, First-Out). This ensures that nodes discovered first are processed first.

BFS(u, v):
    q = an empty queue
    add (0, u) to q               # (distance from start, current vertex)
    visited = set()               # keep track of where we've been
    
    while q is not empty:
        (dist, curr) = q.dequeue()
        
        if curr not in visited:
            mark curr as visited
            
            if curr == v:         # "Early out" if destination found
                return dist
                
            for neighbor in adjacency_list[curr]:
                if neighbor not in visited:
                    q.enqueue((dist + 1, neighbor))
                    
    return "FAIL"                 # No path exists

3. Complexity Analysis

The efficiency of BFS makes it a gold standard for unweighted graphs:

  • Time Complexity: . We visit every vertex once and check every edge once (using an adjacency list).

  • Space Complexity: . In the worst case, we might need to store a large portion of the vertices in the queue.


4. BFS Summary Table

FeatureDescription
Data StructureQueue (FIFO)
Shortest Path?Yes, but only for unweighted graphs
Search StrategyLevel-by-level (Wide)
Ideal Use CaseFinding the minimum number of steps/hops (e.g., Degrees of Kevin Bacon)