Compute Nonnegative Shortest Paths
Find the cheapest distance from a source to every node of a weighted directed graph with the Dijkstra template.
The problem
Implement dijkstra_distances(node_count, edges, source). The nodes are labeled 0 to node_count - 1, and each edge [u, v, weight] goes one way, from u to v, with weight >= 0. Return a list whose entry i is the cost of the cheapest path from source to node i, or -1 if node i cannot be reached. The same pair of nodes may be joined by more than one edge. For example, with edges [[0, 1, 5], [0, 2, 1], [2, 1, 1], [1, 3, 2]] and source 0 the answer is [0, 2, 1, 4]: going 0→2→1 costs 2, which beats the direct edge 0→1 with cost 5.
Starter code
def dijkstra_distances(node_count, edges, source):
passPublic examples
node_count = 4, edges = [[0, 1, 5], [0, 2, 1], [2, 1, 1], [1, 3, 2]], source = 0gives[0, 2, 1, 4]node_count = 3, edges = [[0, 1, 2]], source = 0gives[0, 2, -1]
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
