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)

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.

How Shortest Path (BFS) Works

  1. Start BFS from the source node, marking it visited with a distance of 0.
  2. For each node dequeued, look at its unvisited neighbors.
  3. Set each unvisited neighbor's distance to the current node's distance + 1, and remember the current node as its 'predecessor'.
  4. 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

  1. BFS from A: distance(A)=0, queue: [B, C], distance(B)=1, distance(C)=1
  2. Dequeue B: neighbor D unvisited, distance(D)=2, predecessor(D)=B
  3. Dequeue C: neighbor D already visited, skip
  4. Trace back from D: D <- B <- A

Output: Shortest path: A -> B -> D (length 2)

Graph: Introduction
A set of nodes connected by edges — edges can be one-way or two-way, and optionally carry a weight (cost/distance).
A
B
C
D
E
Unvisited Visited / discovered Current Start
Graph: Introduction
Press ▶ Run to watch it step by step.
Python · Graphs in Code
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 from
Input: Find shortest path from A to D in graph A-B, A-C, B-D, C-D

Behind 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

TimeO(V + E)
SpaceO(V) for distances, predecessors, and the queue

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.