beginnerpathfinding
Breadth-First Search (BFS)
Breadth-First Search (BFS)
BFS explores a graph layer by layer — it visits all nodes at distance 1 before any node at distance 2, all at distance 2 before distance 3, and so on. This level-order exploration guarantees that the first time BFS reaches any node, it has found the shortest path (fewest edges) to it.
How It Works
- Start at the source node, mark it visited, add it to the queue
- Take the front node from the queue
- Visit all its unvisited neighbors, mark them visited, add them to the queue
- Repeat until the queue is empty or the goal is found
The queue (FIFO) is what creates the level-order property — nodes discovered earlier are processed earlier.
Code Snippet
Uses the Graph class from the Graphs and Weighted Graphs article:
def breadth_first_search(graph, start_node: int, goal_node: int) -> list[int]:
"""Find shortest path (fewest hops) from start to goal."""
visited = [False] * graph.num_nodes
parent_of = [-1] * graph.num_nodes
visited[start_node] = True
# Queue implemented as list with head pointer
queue = [start_node]
head = 0
while head < len(queue):
current_node = queue[head]
head += 1
if current_node == goal_node:
break
for neighbor in graph.get_neighbors(current_node):
if not visited[neighbor]:
visited[neighbor] = True
parent_of[neighbor] = current_node
queue.append(neighbor)
# Reconstruct path from goal back to start
path = []
node = goal_node
while node != -1:
path.append(node)
node = parent_of[node]
path.reverse()
return path
Why BFS Guarantees Shortest Path
When BFS discovers a node, it has arrived via the fewest possible edges. This is because:
- All distance-1 nodes are enqueued before any distance-2 node
- All distance-2 nodes are processed before any distance-3 node
- A node is never re-visited (marked visited on discovery, not processing)
This only holds for unweighted graphs. On weighted graphs, fewer hops does not mean lower cost — use Dijkstra instead.
Time and Space Complexity
- Time: O(V + E) — visits each node once, checks each edge once
- Space: O(V) — the queue can hold up to V nodes (entire frontier at maximum width)
When to Use BFS
- Finding shortest path on unweighted graphs
- Level-order tree traversal
- Finding all nodes within k steps of a source
- Checking if two nodes are connected (reachability)
- Social network degree-of-separation queries