oneby7

Advanced Graphs Weighted shortest paths

477. Shortest Path in a DAG

Medium

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

412-352-13012345

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]]

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

2-46-501234

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

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

0

Input: n = 1, edges = []

Output: [0]

Check your understanding

Work out the answer for this input before you write any code.

n = 4 edges = [[0, 1, 2], [0, 2, 6], [2, 1, -5], [1, 3, 1]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 105
  • edges[i].length == 3
  • 0 ≤ ui, vi < n
  • ui ≠ 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.

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.