Shortest-Path Distances with Dijkstra
Problem statement
You are given a directed graph with n vertices numbered from 0 to n - 1. Each edge [u,v,w] permits travel from u to v with nonnegative cost w. Parallel edges and self-loops are allowed.
Return an array of length n where entry v is the minimum total cost of a path from source to v. Return -1 for an unreachable vertex. The distance from the source to itself is 0, using the empty path.
Any correct method within the bounds is accepted; a heap is not required.
Function
shortestDistances(n: int, edges: int[][], source: int) → int[]Examples
Example 1
n = 4edges = [[0,1,4],[0,2,1],[2,1,2],[1,3,1],[2,3,5]]source = 0return = [0,3,1,4]The best routes to vertices 1 and 3 go through vertex 2.
Example 2
n = 3edges = [[1,2,5]]source = 1return = [-1,0,5]Vertex 0 is unreachable from 1. The empty route from the source to itself has distance zero.
Constraints
1 <= n <= 200.0 <= edges.length <= 1000.- Every edge has exactly three integers;
0 <= u,v < nand0 <= w <= 10^6. 0 <= source < n.