Fewest hops between two stations

Graphs Junior Python 3.13+ Reviewed By Best Latest Apps

Pick the fix

Why does BFS find the fewest hops but DFS may not?

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A BFS visits stations in order of distance from the start

Right: all 1-hop stations come before any 2-hop station.

Layer-by-layer order guarantees the first arrival at the goal is along a shortest route when every hop costs the same.

Why not the others?
  • B DFS cannot reach far stations. DFS reaches everything reachable, just not in distance order.
  • C BFS uses less memory. Usually it uses more; the reason is the order of visits.

30-second answer

Breadth-first search from the start explores stations in order of hop count, so the first time it reaches the goal is via the fewest hops. Keep a distance per station and mark stations as you queue them. O(V + E) time and space.

Practise saying it · 30 s. No recording, just a timer

Explain BFS for the fewest hops.

Say your answer out loud, then check which of these points you covered:

  • Queue and distances
  • Mark on push
  • O(V + E)

Deep dive

BFS is correct only because every track costs the same; with different costs use Dijkstra.

Bidirectional BFS (from both ends) can visit far fewer stations on large graphs.

Stop as soon as the goal is reached; no need to explore the rest.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
from collections import deque


def fewest_hops(n: int, tracks: list[list[int]], start: int,
                goal: int) -> int:
    nbrs: list[list[int]] = [[] for _ in range(n)]
    # tracks run both ways
    for u, v in tracks:
        nbrs[u].append(v)
        nbrs[v].append(u)
    dist = [-1] * n
    dist[start] = 0
    queue = deque([start])
    while queue:
        s = queue.popleft()
        if s == goal:
            return dist[s]
        for t in nbrs[s]:
            if dist[t] < 0:
                dist[t] = dist[s] + 1
                queue.append(t)
    return -1

Common mistakes

  • Using DFS, which finds a route but not necessarily the shortest.
  • Marking stations when they are dequeued, which can queue the same station many times.

Senior take & follow-ups

Say why BFS gives the fewest hops (layers in order of distance), then code it.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you return the route itself?

    Show hint

    Store each station's parent and walk back from the goal.

  2. What if some tracks are one-way?

    Show hint

    Build the adjacency list with directed edges; BFS is unchanged.

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.