← All Exercises
Dijkstra Shortest Path with a Heap
advancedpython
Background
Dijkstra's greedy frontier relies on non-negative weights; a binary heap keeps extraction logarithmic, and skipping stale entries keeps the implementation simple.
Problem
Given n nodes, directed edges (u, v, weight), and a source, return the shortest distance from source to every node, using -1 for unreachable nodes. Reject negative weights and out-of-range endpoints.
Input
Node count n, a list of (u, v, weight) directed edges, and a source node.
Output
A list of n distances, with -1 marking nodes unreachable from the source.
Sample tests
Sample 1
Input: n = 4, edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1)], source = 0
Expected: [0, 3, 1, 4]
Sample 2
Input: n = 3, edges = [(0, 1, 5)], source = 2
Expected: [-1, -1, 0]
Your solution
Learning objective
Implement Dijkstra's algorithm with a priority queue, stale-entry filtering, and explicit unreachable handling.