1077. Bellman-Ford — Detect Negative Weight Cycle

HardGraphsShortest PathGraphCycle

Given a directed weighted graph with n nodes and edges [u, v, w] (weights may be negative), determine whether it contains a negative-weight cycle reachable within the graph. Return true or false. The input is JSON {n, edges}.

Input: JSON {n, edges} with edges [u, v, w].

Output: Boolean — true or false.

Examples

Example 1
Input: {"n":4,"edges":[[0,1,1],[1,2,-1],[2,3,-1],[3,0,-1]]}
Output: true
Explanation: The cycle sums to -2.
Example 2
Input: {"n":3,"edges":[[0,1,1],[1,2,2]]}
Output: false
Explanation: No cycle.
Example 3
Input: {"n":3,"edges":[[0,1,-1],[1,2,-1],[2,0,-1]]}
Output: true
Explanation: Negative triangle.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →