Detect a negative cycle
Standard · Write code · about 12 min
A directed graph has n nodes and weighted edges, where edges[i] = [from, to, weight]. Return true when the graph contains a cycle whose weights add up to less than 0, anywhere in the graph.
Example 1
Input:
[4,[[0,1,1],[1,2,-1],[2,3,-1],[3,1,1]]]
Output:
true
The loop 1 → 2 → 3 → 1 costs −1 − 1 + 1 = −1.
Example 2
Input:
[3,[[0,1,2],[1,2,-1],[0,2,3]]]
Output:
false
A negative edge alone is not a negative cycle.
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ edges.length ≤ 1,000
- -100 ≤ weight ≤ 100
Learn the idea first: Bellman-Ford and negative edges, a visual lesson.
More Bellman-Ford and negative edges problems
- Rounds needed Warm-up
- Implement Bellman-Ford Standard
- Cheapest flights within k stops Standard