Data Structures · Visualization
Graph: Shortest Path (BFS)
Graph
In an unweighted graph (where every edge counts equally, with no different 'costs'), BFS naturally finds the shortest path between two nodes, because it explores the graph level by level, so the first time it reaches a node is guaranteed to be via the shortest possible route. Time: O(V + E). Space: O(V) for distances, predecessors, and the queue.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Shortest Path (BFS)
GraphIn an unweighted graph (where every edge counts equally, with no different 'costs'), BFS naturally finds the shortest path between two nodes, because it explores the graph level by level, so the first time it reaches a node is guaranteed to be via the shortest possible route.
How Shortest Path (BFS) Works
- Start BFS from the source node, marking it visited with a distance of 0.
- For each node dequeued, look at its unvisited neighbors.
- Set each unvisited neighbor's distance to the current node's distance + 1, and remember the current node as its 'predecessor'.
- Once the target node is dequeued (or all reachable nodes are processed), trace back through predecessors from the target to reconstruct the shortest path.
Shortest Path (BFS) Worked Example
Input: Find shortest path from A to D in graph A-B, A-C, B-D, C-D
- BFS from A: distance(A)=0, queue: [B, C], distance(B)=1, distance(C)=1
- Dequeue B: neighbor D unvisited, distance(D)=2, predecessor(D)=B
- Dequeue C: neighbor D already visited, skip
- Trace back from D: D <- B <- A
Output: Shortest path: A -> B -> D (length 2)
Press ▶ Run to watch it step by step.
from collections import deque
def shortest_unweighted(graph, start, target):
q = deque([(start, 0)])
seen = {start}
while q:
v, d = q.popleft()
if v == target:
return d
for nxt in graph[v]:
if nxt not in seen:
seen.add(nxt)
q.append((nxt, d + 1))
return -1
# example: shortest path fromBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Shortest Path (BFS) Time & Space Complexity
When to Use Shortest Path (BFS)
- Finding the fewest number of connections between two people in a social network
- Simple maze/grid pathfinding where all moves cost the same
- Network hop-count analysis
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.