oneby7

Advanced Graphs Weighted shortest paths

483. Bellman-Ford algorithm

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

63-425-10src1234

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

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

5-310src123

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

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

1-1-10src12

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

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

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

Constraints

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

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.