Advanced Graphs Weighted shortest paths
479. Print the Shortest Path
You are given an undirected graph with n vertices, numbered from 1 to n. Each triple [u, v, w] in
edges is an edge of weight w between vertices u and v, and it can be used in both directions.
Return a shortest path from vertex 1 to vertex n, as the list of the vertices along it, starting with 1
and ending with n. The weight of a path is the sum of the weights of its edges, and a shortest path is one
whose weight is as small as possible. If no path leads from 1 to n, return [-1].
Often several shortest paths exist, and any of them is correct. The result shows the weight of the path you
return, as a path of weight 5. [-1] shows as [-1]. Any other answer shows what is wrong with it, such as
no edge joins 2 and 5.
Example 1
Input: n = 5
edges = [[1, 2, 2],
[2, 5, 5],
[2, 3, 4],
[1, 4, 1],
[4, 3, 3],
[3, 5, 1]]
[1,4,3,5]Explanation: The path 1 → 4 → 3 → 5 has weight 1 + 3 + 1 = 5. The path 1 → 2 → 5 has fewer edges, but its weight is 2 + 5 = 7.
Example 2
Input: n = 4, edges = [[1, 2, 3], [3, 4, 6]]
[-1]Explanation: Vertices 1 and 2 are joined, and so are 3 and 4, but no edge links the two pairs. No path leads from 1 to 4.
Example 3
Input: n = 3
edges = [[2, 1, 4],
[1, 2, 9],
[3, 2, 1],
[1, 3, 6]]
[1,2,3]Explanation: Two edges join 1 and 2, and the lighter one has weight 4. Going through vertex 2 costs 4 + 1 = 5, less
than the direct edge of weight 6. The edges [2,1,4] and [3,2,1] are used from their second vertex to
their first.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 105edges[i] = [u, v, w], with1 ≤ u, v ≤ nand1 ≤ w ≤ 109- Two edges can join the same two vertices, and an edge can join a vertex to itself.
Clarifying questions
What you would ask an interviewer before writing any code.