Cheapest path with Dijkstra

Link-state routers have the whole map and find the cheapest path with Dijkstra's algorithm.

What to build

A program that finds the cheapest path from router 1 to router n.

Requirements

  • Links join two routers both ways, each with a cost. There may be several links between the same two routers.
  • Print cost C and path followed by the routers on the way, from 1 to n.
  • If two paths cost the same, print the path whose list of router numbers is smaller in dictionary order (compare the first router where they differ).
  • If router n cannot be reached, print unreachable.

Input

Line 1: n and m. Then m lines u v c: a link between routers u and v with cost c.

Output

Two lines, cost C and path 1 ... n, or unreachable.

Constraints

1 ≤ n ≤ 50; 0 ≤ m ≤ 200; 1 ≤ c ≤ 100.

Example

Input:

4 5
1 2 1
2 3 2
1 3 5
3 4 1
2 4 6

Output:

cost 4
path 1 2 3 4

Why it works

Dijkstra settles routers in order of cost. Keeping the whole path in the heap entry makes equal-cost ties break by the smallest path, so the answer is the same every time.

Examples

Example 1 · Input
4 5
1 2 1
2 3 2
1 3 5
3 4 1
2 4 6
Expected output
cost 4
path 1 2 3 4
Example 2 · Input
3 1
1 2 4
Expected output
unreachable

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Use a heap of (cost, path) pairs, starting with (0, [1]). Python compares the path lists when costs tie, which gives the smallest path.

Hint 2

Pop the smallest pair. If its router is already settled, skip it. If it is the last router, you are done.

Hint 3

Push (cost + link, path + [neighbour]) for each neighbour not yet settled. Links work both ways.

Solution

Show one correct solution (try it yourself first)
import heapq

n, m = map(int, input().split())
adj = {i: [] for i in range(1, n + 1)}
for _ in range(m):
    u, v, c = map(int, input().split())
    adj[u].append((v, c))
    adj[v].append((u, c))
heap = [(0, [1])]
done = set()
answer = None
while heap:
    cost, path = heapq.heappop(heap)
    r = path[-1]
    if r in done:
        continue
    done.add(r)
    if r == n:
        answer = (cost, path)
        break
    for v, c in adj[r]:
        if v not in done:
            heapq.heappush(heap, (cost + c, path + [v]))
if answer is None:
    print("unreachable")
else:
    print("cost", answer[0])
    print("path", *answer[1])

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Routing algorithms: link state and distance vector →