Advanced Graphs Weighted shortest paths
478. Dijkstra's Algorithm
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
Input: n = 5
edges = [[0, 1, 4],
[0, 2, 1],
[2, 1, 2],
[1, 3, 5],
[2, 3, 8],
[3, 4, 3]]
src = 0
[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
Input: n = 4, edges = [[1, 0, 6], [2, 3, 0]], src = 0
[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
Input: n = 4
edges = [[0, 1, 1000000000],
[1, 2, 1000000000],
[2, 3, 1000000000],
[3, 3, 7]]
src = 0
[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.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 105edges[i] = [u, v, w], with0 ≤ u, v < nand0 ≤ w ≤ 1090 ≤ 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.