50. Shortest Routes from a Starting Point
Easy
A network of routes is represented by n nodes numbered from 0 to n - 1 and a list of directed routes. Each route connects one node to another and has a non-negative weight.
Given n, arestas, and origem, calculate the shortest distance from origem to every node. Return a list of length n, where position i contains the distance to node i. Use -1 when there is no route from the source to that node.
Each item in arestas has the form [inicio, fim, peso], indicating a directed route from inicio to fim with the given weight. Nodes are numbered starting at zero.
Example 1
Input: n = 5, arestas = [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 3, 5]], origem = 0
Output: [0, 3, 1, 4, -1]
Explanation: The shortest route to node 1 passes through node 2; node 4 is unreachable.
Example 2
Input: n = 4, arestas = [], origem = 2
Output: [-1, -1, 0, -1]
Explanation: The source has distance zero from itself, and no other node is reachable.
Example 3
Input: n = 4, arestas = [[0, 1, 0], [1, 2, 3], [0, 2, 5], [2, 1, 1], [3, 0, 2]], origem = 0
Output: [0, 0, 3, -1]
Explanation: The route to node 2 becomes shorter through node 1, and there is no route from the source to node 3.
Constraints
- 1 <= n <= 10^4
- 0 <= arestas.length <= 2 * 10^4
- Each item in arestas contains exactly three integers: [inicio, fim, peso].
- 0 <= inicio, fim < n
- 0 <= peso <= 10^6
- 0 <= origem < n
GraphsHeap
Saved in this browser
Caso 1
n =
5
arestas =
[[0,1,4],[0,2,1],[2,1,2],[1,3,1],[2,3,5]]
origem =
0
Expected =
[0,3,1,4,-1]
Caso 2
n =
4
arestas =
[]
origem =
2
Expected =
[-1,-1,0,-1]
Caso 3
n =
4
arestas =
[[0,1,0],[1,2,3],[0,2,5],[2,1,1],[3,0,2]]
origem =
0
Expected =
[0,0,3,-1]
Run checks these 3 cases. Submit runs all 11, including hidden ones.