Code

Closest Island First

BFS counts bridges. But couriers care about minutes, and every bridge takes a different time. A route with more bridges can be faster! For that, we need Dijkstra's algorithm (say "DIKE-stra").

The idea

BFS used a queue: first found, first explored. Dijkstra uses a heap instead: the island with the smallest time so far is explored next. That is a priority queue, just like in The Quest Heap.

best = {start: 0}          # fastest time found so far
heap = [(0, start)]        # (time, island)
while heap:
    time, island = heapq.heappop(heap)
    ...

For each bridge (nxt, minutes) out of island, the new time is time + minutes. If nxt has no time yet, or the new time is smaller, save it in best and push (new, nxt) on the heap.

Stale entries

An island can be pushed more than once, when a faster time turns up later. The old, slower entry is still in the heap. When you pop an entry whose time is bigger than best[island], it is stale. Skip it with continue.

A tiny trace

Depot -> Mill (4)   Depot -> Reef (1)   Reef -> Mill (2)
pop (0, Depot): best Mill = 4, Reef = 1
pop (1, Reef):  Mill 1 + 2 = 3 is faster! best Mill = 3
pop (3, Mill):  done with Mill
pop (4, Mill):  4 > best[Mill], stale: skip

Dijkstra works as long as no bridge takes negative time.

Assignment

Complete shortest_times(network, start). network maps an island to a list of (neighbor, minutes) tuples.

  1. Loop while the heap isn't empty and pop the smallest (time, island).
  2. Skip stale entries: time > best[island].
  3. For each bridge from island (use network.get(island, [])), save and push any time that beats the one in best.
  4. Return best: the fastest time to every reachable island.