Advanced Graphs Weighted shortest paths
483. Bellman-Ford algorithm
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. An edge can be used only from u to v, and
a weight can be negative.
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 length of the shortest path from src to vertex v. The entry for src itself is 0. If no path leads
from src to a vertex, its entry is 100000000 (108).
A negative cycle is a path that starts and ends at the same vertex and whose weights add up to less than 0.
Each trip round it makes a path shorter, without end. If src can reach a negative cycle, return [-1]
instead. A negative cycle that src cannot reach does not change the answer.
Example 1
Input: n = 5
edges = [[0, 1, 6],
[0, 2, 3],
[2, 1, -4],
[1, 3, 2],
[2, 3, 5],
[3, 4, -1]]
src = 0
[0,-1,3,1,0]Explanation: Vertex 1 is closest through vertex 2, at 3 + (−4) = −1, which beats the direct edge of 6. From there vertex 3 is at −1 + 2 = 1, and vertex 4 at 1 + (−1) = 0.
Example 2
Input: n = 4
edges = [[0, 1, 5], [2, 3, -3], [3, 2, 1]]
src = 0
[0,5,100000000,100000000]Explanation: The cycle 2 → 3 → 2 adds up to −2, so it is a negative cycle. No path leads from vertex 0 to it, so it does not matter, and vertices 2 and 3 get 108.
Example 3
Input: n = 3
edges = [[0, 1, 1], [1, 2, -1], [2, 1, -1]]
src = 0
[-1]Explanation: Vertex 0 reaches the cycle 1 → 2 → 1, whose weights add up to −2. Each trip round it makes the paths to
vertices 1 and 2 shorter, so the answer is [-1].
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 50000 ≤ edges.length ≤ 104edges[i] = [u, v, w], with0 ≤ u, v < nand-104 ≤ w ≤ 1040 ≤ src < n- Two edges can join the same two vertices, and an edge can lead from a vertex back to itself.
Clarifying questions
What you would ask an interviewer before writing any code.