Advanced Graphs Weighted shortest paths
477. Shortest Path in a DAG
You are given a directed graph with n vertices, numbered from 0 to n - 1. Each triple [u, v, w] in
edges is an edge from vertex u to vertex v with weight w. A weight can be negative. The graph has no
cycles: if you follow edges from any vertex, you never come back to it.
The length of a path is the sum of the weights of its edges. Return an array of length n whose entry v is
the smallest length of any path from vertex 0 to vertex v. The entry for vertex 0 is 0. If no path
leads from vertex 0 to a vertex, its entry is 2147483647, the largest 32-bit integer.
Example 1
Input: n = 6
edges = [[0, 1, 4],
[0, 2, 1],
[2, 1, 2],
[1, 3, -3],
[2, 3, 5],
[3, 4, 2],
[4, 5, -1],
[2, 5, 3]]
[0,3,1,0,2,1]Explanation: Vertex 1 costs 1 + 2 = 3 through vertex 2, less than its own edge of 4. Vertex 3 then costs 3 − 3 = 0, and vertex 5 costs 0 + 2 − 1 = 1 through vertices 3 and 4, less than the 1 + 3 = 4 of the edge from vertex 2.
Example 2
Input: n = 5
edges = [[3, 0, 2],
[0, 2, -4],
[2, 4, 6],
[3, 1, -5]]
[0,2147483647,-4,2147483647,2]Explanation: Vertex 2 costs -4 and vertex 4 costs -4 + 6 = 2. No path leads from vertex 0 to vertex 1 or vertex 3, so their entries are 2147483647. The edge from vertex 3 into vertex 0 does not count, because every path starts at vertex 0.
Example 3
Input: n = 1, edges = []
[0]Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 105edges[i].length == 30 ≤ ui, vi < nui ≠ vi-104 ≤ wi ≤ 104- The graph has no cycles. Two edges can join the same two vertices.
Clarifying questions
What you would ask an interviewer before writing any code.