AlgoFrames

Implement Bellman-Ford

Standard · Write code · about 12 min

A directed graph has n nodes and edges, where edges[i] = [from, to, weight]. Weights may be negative, but no negative cycle exists. Return dist, where dist[v] is the shortest distance from source to v.

Use -1 for an unreachable node. Tests never have a reachable node whose shortest distance is -1.

Example 1

Input:

[5,[[1,3,2],[2,1,-3],[3,4,3],[0,1,4],[0,2,5],[2,4,6]],0]

Output:

[0,2,5,4,7]

Node 1 is 2 away through the rebate edge 2→1.

Example 2

Input:

[4,[[0,1,3],[0,2,1],[2,1,1],[1,3,2]],0]

Output:

[0,2,1,4]

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ 1,000
  • -100 ≤ weight ≤ 100
  • 0 ≤ source < n
  • No negative cycle

Learn the idea first: Bellman-Ford and negative edges, a visual lesson.

More Bellman-Ford and negative edges problems