oneby7

Advanced Graphs Weighted shortest paths

479. Print the Shortest Path

Medium

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

25413112345

Input: n = 5 edges = [[1, 2, 2], [2, 5, 5], [2, 3, 4], [1, 4, 1], [4, 3, 3], [3, 5, 1]]

Output: [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

361234

Input: n = 4, edges = [[1, 2, 3], [3, 4, 6]]

Output: [-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

4916123

Input: n = 3 edges = [[2, 1, 4], [1, 2, 9], [3, 2, 1], [1, 3, 6]]

Output: [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.

n = 4 edges = [[1, 4, 10], [1, 2, 3], [2, 3, 3], [3, 4, 3], [2, 4, 8]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 105
  • edges[i] = [u, v, w], with 1 ≤ u, v ≤ n and 1 ≤ 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.