Fewest links or least time: BFS or Dijkstra?
Question
A delivery network has four nodes, S, A, B and T, joined by one-way links. Each link takes some minutes:
| link | minutes |
|---|---|
| S → T | 11 |
| S → A | 2 |
| A → B | 3 |
| B → T | 1 |
- Which route from S to T uses the fewest links?
- Which route takes the least time?
For each question, name the algorithm you would use and explain why it fits.
Show hints (3)
- "TWO DIFFERENT QUESTIONS"
One question counts links. The other adds up minutes. Can the route with the fewest links be the slowest one?
- "FEWEST LINKS"
Breadth-first search (BFS) visits every node one link away, then two links away, and so on. The first time it reaches T, it has used the fewest links. It never looks at the minutes.
- "LEAST TIME"
Dijkstra's algorithm always continues from the node with the smallest known time. After S you know A = 2 and T = 11. Which node comes next, and what does it change?
Show checked explanation
Fewest links is S → T: one link, 11 minutes. BFS finds it, because it explores everything one link away before anything two links away. Least time is S → A → B → T: 6 minutes. Dijkstra's algorithm finds it by adding up minutes. It works here because no link has a negative time.
import heapq def fastest(graph, start, goal): best, heap = {start: 0}, [(0, start)] while heap: time, node = heapq.heappop(heap) if time > best[node]: continue # old entry: a faster time was found later if node == goal: return time for next_node, minutes in graph[node].items(): if time + minutes < best.get(next_node, float("inf")): best[next_node] = time + minutes heapq.heappush(heap, (time + minutes, next_node)) return None # the goal can't be reached graph = {"S": {"T": 11, "A": 2}, "A": {"B": 3}, "B": {"T": 1}, "T": {}} print(fastest(graph, "S", "T"))
6
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
BFS answers question 1. It uses a queue, usually collections.deque, and explores in layers. The first layer from S is T and A, both one link away. T is already there, so the route with the fewest links is S → T. BFS never reads the minutes, so the 11 doesn't matter.
Dijkstra's algorithm answers question 2. In the code, best holds the best time found so far for each node, and heap holds (time, node) pairs. Each step takes the pair with the smallest time.
| taken from the heap | what changes |
|---|---|
| S at 0 | A = 2, T = 11 |
| A at 2 | B = 5 |
| B at 5 | T = 6, better than 11 |
| T at 6 | T is the goal: the answer is 6 |
T was first seen at 11 minutes, but that time was not final. A time is final only when its node comes off the heap. When T comes off at 6, everything left in the heap costs 6 or more. No link has a negative time, so extra links can't bring those routes below 6.
The heap still holds (11, "T") at the end. heapq can't change an entry that is already in the heap, so each better time is pushed as a new entry. When an old entry comes out later, if time > best[node] skips it.
If the goal can't be reached, the heap runs empty and the function returns None. If the start is the goal, it returns 0.
BFS runs in O(V + E), where V is the number of nodes and E the number of links. Dijkstra with a heap runs in O((V + E) log V).
Common mistakes
- Using BFS for the least-time question. It returns S → T, which takes 11 minutes, because it counts links and ignores minutes.
- Stopping as soon as you first see T, as BFS does. That gives 11 minutes. In Dijkstra, a time is final only when its node comes off the heap.
- Pushing
(time, node)when nodes don't support<, such as objects of your own class. When two times are equal, Python compares the nodes and raisesTypeError. Push(time, count, node)with a running counter.
Follow-up questions
- "What if some links have negative weights?" Dijkstra can return a wrong answer. Take a new graph: S → T (2), S → K (5) and K → T (-7). The code takes T off the heap at 2 and returns 2. But S → K → T costs -2: the negative link made a longer route cheaper. Use Bellman–Ford instead. It also detects negative cycles, where no shortest route exists.
- "Return the route, not only the time." Keep a
prevdict. Whenever a node gets a better time, store the node you came from. When the goal comes off the heap, followprevback to the start and reverse the list. Here that gives S → A → B → T. - "When is BFS enough, even with weights?" When every link has the same positive weight. Then a route's time is its number of links times that weight, so the fewest links also means the least time. With different weights, as here, BFS gives no such promise.
What a strong answer covers
Asks what "shortest" means before choosing. Gives both routes with their numbers. Explains why a time is final only when it leaves the heap, and why that needs non-negative weights. Handles old heap entries.
Open in interactive practice deck →