oneby7

Advanced Graphs Weighted shortest paths

478. Dijkstra's Algorithm

Medium

You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each row edges[i] = [u, v, w] is an edge of length w between vertices u and v, and it can be used in both directions.

You are also given a starting vertex src. Return an array of length n whose entry v is the length of the shortest path from src to vertex v. The length of a path is the sum of the lengths of its edges. The entry for src itself is 0. If no path leads from src to a vertex, its entry is -1.

Example 1

4125830src1234

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

Output: [0,3,1,8,11]

Explanation: Vertex 2 is 1 away. Vertex 1 is 1 + 2 = 3 away through vertex 2, which beats the direct edge of length 4. Vertex 3 is 3 + 5 = 8 away through vertex 1, and vertex 4 is 8 + 3 = 11 away.

Example 2

600src123

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

Output: [0,6,-1,-1]

Explanation: The edge [1, 0, 6] can be used from vertex 0 too, so vertex 1 is 6 away. No edge joins vertices 2 and 3 to the other two, so their entries are -1.

Example 3

10⁹10⁹10⁹70src123

Input: n = 4 edges = [[0, 1, 1000000000], [1, 2, 1000000000], [2, 3, 1000000000], [3, 3, 7]] src = 0

Output: [0,1000000000,2000000000,3000000000]

Explanation: Each edge on the way adds 109, so vertex 3 is 3 × 109 away. The edge [3, 3, 7] joins vertex 3 to itself and never makes a path shorter.

Check your understanding

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

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

Constraints

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