Detect a negative cycle in a Graph (original) (raw)

Last Updated : 29 Apr, 2026

Given a directed weighted graph, your task is to find whether the given graph contains any negative cycles that are reachable from the source vertex (e.g., node 0).

**Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value.

**Examples:

**Input: V = 4, edges[][] = [[0, 3, 6], [1, 0, 4], [1, 2, 6], [3, 1, 2]]

Example1

**Output: 0
**Explanation : Cycle 1 → 0 → 3 → 1 has total weight 6 + 4 + 2 = 12, which is positive, so no negative weight cycle exists.

**Input : V = 4, edges[][] = [[1, 0, 4], [3, 1, -2], [1, 2, -6], [2, 3, 5]]
Example2**Output: 1
**Explanation : There is a cycle 1 → 2 → 3 → 1 with total weight -3, which is negative, so a negative weight cycle exists.

Try It Yourselfredirect icon

Detecting Negative Weight Cycle using Bellman-Ford – O(V * E) Time and O(V) Space

The idea is to use the Bellman-Ford Algorithm where we relax all edges **V-1 times to compute shortest paths. In a normal graph, distances stabilize after these iterations. If we can still relax any edge after that, it means the distance is continuously decreasing, which happens only when there is a **negative weight cycle in the graph.

#include #include using namespace std;

// Function to detect negative weight cycle bool isNegativeCycle(int n, vector<vector> &edges) {

vector<int> dist(n, 0);

// Relax edges n-1 times
for (int i = 0; i < n - 1; i++)
{
    for (auto edge : edges)
    {
        int u = edge[0];
        int v = edge[1];
        int wt = edge[2];

        if (dist[u] + wt < dist[v])
        {
            dist[v] = dist[u] + wt;
        }
    }
}

// Check for negative cycle
for (auto edge : edges)
{
    int u = edge[0];
    int v = edge[1];
    int wt = edge[2];

    if (dist[u] + wt < dist[v])
    {
        // negative cycle found
        return true; 
    }
}
return false; 

}

int main() {

int n = 3;

vector<vector<int>> edges = {{0, 1, -1}, {1, 2, -2}, {2, 0, -3}};

if (isNegativeCycle(n, edges))
{
    cout << "true";
}
else
{
    cout << "false";
}

return 0;

}

Java

import java.util.*;

class GFG {

// Function to detect negative weight cycle
public static boolean isNegativeCycle(int n, int[][] edges) {

    int[] dist = new int[n];
    Arrays.fill(dist, 0);

    // Relax edges n-1 times
    for (int i = 0; i < n - 1; i++) {
        for (int[] edge : edges) {
            int u = edge[0];
            int v = edge[1];
            int wt = edge[2];

            if (dist[u] + wt < dist[v]) {
                dist[v] = dist[u] + wt;
            }
        }
    }

    // Check for negative cycle
    for (int[] edge : edges) {
        int u = edge[0];
        int v = edge[1];
        int wt = edge[2];

        if (dist[u] + wt < dist[v]) {
            return true;
        }
    }

    return false;
}

public static void main(String[] args) {

    int n = 3;

    int[][] edges = {
        {0, 1, -1},
        {1, 2, -2},
        {2, 0, -3}
    };

    System.out.println(isNegativeCycle(n, edges));
}

}

Python

def is_negative_cycle(n, edges): dist = [0] * n

# Relax edges n-1 times
for _ in range(n - 1):
    for u, v, wt in edges:
        if dist[u] + wt < dist[v]:
            dist[v] = dist[u] + wt

# Check for negative cycle
for u, v, wt in edges:
    if dist[u] + wt < dist[v]:
        return True

return False

Driver code

n = 3 edges = [ [0, 1, -1], [1, 2, -2], [2, 0, -3] ]

print(is_negative_cycle(n, edges))

C#

using System;

class GFG {

// Function to detect negative weight cycle
public static bool isNegativeCycle(int n, int[,] edges) {

    int[] dist = new int[n];
    int m = edges.GetLength(0);

    // Initialize distances
    for (int i = 0; i < n; i++)
        dist[i] = 0;

    // Relax edges n-1 times
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < m; j++) {
            int u = edges[j, 0];
            int v = edges[j, 1];
            int wt = edges[j, 2];

            if (dist[u] + wt < dist[v]) {
                dist[v] = dist[u] + wt;
            }
        }
    }

    // Check for negative cycle
    for (int j = 0; j < m; j++) {
        int u = edges[j, 0];
        int v = edges[j, 1];
        int wt = edges[j, 2];

        if (dist[u] + wt < dist[v]) {
            return true;
        }
    }

    return false;
}

public static void Main() {

    int n = 3;

    int[,] edges = {
        {0, 1, -1},
        {1, 2, -2},
        {2, 0, -3}
    };

    Console.WriteLine(isNegativeCycle(n, edges));
}

}

JavaScript

function isNegativeCycle(n, edges) { let dist = new Array(n).fill(0);

// Relax edges n-1 times
for (let i = 0; i < n - 1; i++) {
    for (let [u, v, wt] of edges) {
        if (dist[u] + wt < dist[v]) {
            dist[v] = dist[u] + wt;
        }
    }
}

// Check for negative cycle
for (let [u, v, wt] of edges) {
    if (dist[u] + wt < dist[v]) {
        return true;
    }
}

return false;

}

// Driver code let n = 3; let edges = [ [0, 1, -1], [1, 2, -2], [2, 0, -3] ];

console.log(isNegativeCycle(n, edges));

`

**Related articles: