Bellman-Ford Algorithm - Problem
The Bellman-Ford algorithm is a single-source shortest path algorithm that can handle graphs with negative edge weights, unlike Dijkstra's algorithm. It can also detect negative weight cycles in the graph.
Given a weighted directed graph represented as an edge list and a source vertex, implement the Bellman-Ford algorithm to:
1. Find the shortest distances from the source to all other vertices
2. Detect if there's a negative weight cycle reachable from the source
Return a result object containing:
distances: Array of shortest distances from source to each vertex (usefloat('inf')for unreachable vertices)hasNegativeCycle: Boolean indicating whether a negative weight cycle exists
If a negative cycle exists, the distances array should still contain the distances computed before cycle detection.
Input & Output
Example 1 — Basic Graph with Negative Edge
$
Input:
n = 5, edges = [[0,1,4],[0,2,2],[1,2,-3],[2,3,3],[1,3,2],[1,4,3],[3,4,1]], source = 0
›
Output:
{"distances":[0,4,-1,2,3],"hasNegativeCycle":false}
💡 Note:
From source 0: direct to 1 costs 4, direct to 2 costs 2, then 2→1 with weight -3 makes path 0→2→1 cost -1, which is better than direct path to 1. No negative cycles exist.
Example 2 — Graph with Negative Cycle
$
Input:
n = 3, edges = [[0,1,1],[1,2,-3],[2,1,1]], source = 0
›
Output:
{"distances":[0,1,-2],"hasNegativeCycle":true}
💡 Note:
Path 0→1→2 costs -2, but vertices 1 and 2 form a negative cycle (1→2→1 = -3+1 = -2), allowing infinite cost reduction.
Example 3 — Disconnected Graph
$
Input:
n = 4, edges = [[0,1,2],[2,3,-1]], source = 0
›
Output:
{"distances":[0,2,"Infinity","Infinity"],"hasNegativeCycle":false}
💡 Note:
Source 0 can reach vertex 1 with cost 2, but vertices 2 and 3 are unreachable from source 0, so their distances remain infinity.
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ edges.length ≤ n*(n-1)
- edges[i] = [u, v, weight] where 0 ≤ u, v < n
- -100 ≤ weight ≤ 100
- 0 ≤ source < n
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code