# Detect a negative cycle in a Graph | (Bellman Ford)

We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative.

Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path.

Examples:

Input : 4 4 0 1 1 1 2 -1 2 3 -1 3 0 -1 Output : Yes The graph contains a negative cycle.

The idea is to use Bellman Ford Algorithm.

Below is algorithm find if there is a negative weight cycle reachable from given source.

**1)** Initialize distances from source to all vertices as infinite and distance to source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.

**2)** This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph.

…..**a)** Do following for each edge u-v

………………If dist[v] > dist[u] + weight of edge uv, then update dist[v]

………………….dist[v] = dist[u] + weight of edge uv

**3)** This step reports if there is a negative weight cycle in graph. Do following for each edge u-v

……If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle”

The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle.

## C++

`// A C++ program to check if a graph contains negative ` `// weight cycle using Bellman-Ford algorithm. This program ` `// works only if all vertices are reachable from a source ` `// vertex 0. ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// a structure to represent a weighted edge in graph ` `struct` `Edge { ` ` ` `int` `src, dest, weight; ` `}; ` ` ` `// a structure to represent a connected, directed and ` `// weighted graph ` `struct` `Graph { ` ` ` `// V-> Number of vertices, E-> Number of edges ` ` ` `int` `V, E; ` ` ` ` ` `// graph is represented as an array of edges. ` ` ` `struct` `Edge* edge; ` `}; ` ` ` `// Creates a graph with V vertices and E edges ` `struct` `Graph* createGraph(` `int` `V, ` `int` `E) ` `{ ` ` ` `struct` `Graph* graph = ` `new` `Graph; ` ` ` `graph->V = V; ` ` ` `graph->E = E; ` ` ` `graph->edge = ` `new` `Edge[graph->E]; ` ` ` `return` `graph; ` `} ` ` ` `// The main function that finds shortest distances ` `// from src to all other vertices using Bellman- ` `// Ford algorithm. The function also detects ` `// negative weight cycle ` `bool` `isNegCycleBellmanFord(` `struct` `Graph* graph, ` ` ` `int` `src) ` `{ ` ` ` `int` `V = graph->V; ` ` ` `int` `E = graph->E; ` ` ` `int` `dist[V]; ` ` ` ` ` `// Step 1: Initialize distances from src ` ` ` `// to all other vertices as INFINITE ` ` ` `for` `(` `int` `i = 0; i < V; i++) ` ` ` `dist[i] = INT_MAX; ` ` ` `dist[src] = 0; ` ` ` ` ` `// Step 2: Relax all edges |V| - 1 times. ` ` ` `// A simple shortest path from src to any ` ` ` `// other vertex can have at-most |V| - 1 ` ` ` `// edges ` ` ` `for` `(` `int` `i = 1; i <= V - 1; i++) { ` ` ` `for` `(` `int` `j = 0; j < E; j++) { ` ` ` `int` `u = graph->edge[j].src; ` ` ` `int` `v = graph->edge[j].dest; ` ` ` `int` `weight = graph->edge[j].weight; ` ` ` `if` `(dist[u] != INT_MAX && dist[u] + weight < dist[v]) ` ` ` `dist[v] = dist[u] + weight; ` ` ` `} ` ` ` `} ` ` ` ` ` `// Step 3: check for negative-weight cycles. ` ` ` `// The above step guarantees shortest distances ` ` ` `// if graph doesn't contain negative weight cycle. ` ` ` `// If we get a shorter path, then there ` ` ` `// is a cycle. ` ` ` `for` `(` `int` `i = 0; i < E; i++) { ` ` ` `int` `u = graph->edge[i].src; ` ` ` `int` `v = graph->edge[i].dest; ` ` ` `int` `weight = graph->edge[i].weight; ` ` ` `if` `(dist[u] != INT_MAX && dist[u] + weight < dist[v]) ` ` ` `return` `true` `; ` ` ` `} ` ` ` ` ` `return` `false` `; ` `} ` ` ` `// Driver program to test above functions ` `int` `main() ` `{ ` ` ` `/* Let us create the graph given in above example */` ` ` `int` `V = 5; ` `// Number of vertices in graph ` ` ` `int` `E = 8; ` `// Number of edges in graph ` ` ` `struct` `Graph* graph = createGraph(V, E); ` ` ` ` ` `// add edge 0-1 (or A-B in above figure) ` ` ` `graph->edge[0].src = 0; ` ` ` `graph->edge[0].dest = 1; ` ` ` `graph->edge[0].weight = -1; ` ` ` ` ` `// add edge 0-2 (or A-C in above figure) ` ` ` `graph->edge[1].src = 0; ` ` ` `graph->edge[1].dest = 2; ` ` ` `graph->edge[1].weight = 4; ` ` ` ` ` `// add edge 1-2 (or B-C in above figure) ` ` ` `graph->edge[2].src = 1; ` ` ` `graph->edge[2].dest = 2; ` ` ` `graph->edge[2].weight = 3; ` ` ` ` ` `// add edge 1-3 (or B-D in above figure) ` ` ` `graph->edge[3].src = 1; ` ` ` `graph->edge[3].dest = 3; ` ` ` `graph->edge[3].weight = 2; ` ` ` ` ` `// add edge 1-4 (or A-E in above figure) ` ` ` `graph->edge[4].src = 1; ` ` ` `graph->edge[4].dest = 4; ` ` ` `graph->edge[4].weight = 2; ` ` ` ` ` `// add edge 3-2 (or D-C in above figure) ` ` ` `graph->edge[5].src = 3; ` ` ` `graph->edge[5].dest = 2; ` ` ` `graph->edge[5].weight = 5; ` ` ` ` ` `// add edge 3-1 (or D-B in above figure) ` ` ` `graph->edge[6].src = 3; ` ` ` `graph->edge[6].dest = 1; ` ` ` `graph->edge[6].weight = 1; ` ` ` ` ` `// add edge 4-3 (or E-D in above figure) ` ` ` `graph->edge[7].src = 4; ` ` ` `graph->edge[7].dest = 3; ` ` ` `graph->edge[7].weight = -3; ` ` ` ` ` `if` `(isNegCycleBellmanFord(graph, 0)) ` ` ` `cout << ` `"Yes"` `; ` ` ` `else` ` ` `cout << ` `"No"` `; ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Java

`// Java program to check if a graph contains negative ` `// weight cycle using Bellman-Ford algorithm. This program ` `// works only if all vertices are reachable from a source ` `// vertex 0. ` `import` `java.util.*; ` ` ` `class` `GFG { ` ` ` ` ` `// a structure to represent a weighted edge in graph ` ` ` `static` `class` `Edge { ` ` ` `int` `src, dest, weight; ` ` ` `} ` ` ` ` ` `// a structure to represent a connected, directed and ` ` ` `// weighted graph ` ` ` `static` `class` `Graph { ` ` ` ` ` `// V-> Number of vertices, E-> Number of edges ` ` ` `int` `V, E; ` ` ` ` ` `// graph is represented as an array of edges. ` ` ` `Edge edge[]; ` ` ` ` ` `} ` ` ` ` ` `// Creates a graph with V vertices and E edges ` ` ` `static` `Graph createGraph(` `int` `V, ` `int` `E) { ` ` ` `Graph graph = ` `new` `Graph(); ` ` ` `graph.V = V; ` ` ` `graph.E = E; ` ` ` `graph.edge = ` `new` `Edge[graph.E]; ` ` ` ` ` `for` `(` `int` `i = ` `0` `; i < graph.E; i++) { ` ` ` `graph.edge[i] = ` `new` `Edge(); ` ` ` `} ` ` ` ` ` `return` `graph; ` ` ` `} ` ` ` ` ` `// The main function that finds shortest distances ` ` ` `// from src to all other vertices using Bellman- ` ` ` `// Ford algorithm. The function also detects ` ` ` `// negative weight cycle ` ` ` `static` `boolean` `isNegCycleBellmanFord(Graph graph, ` `int` `src) { ` ` ` `int` `V = graph.V; ` ` ` `int` `E = graph.E; ` ` ` `int` `[] dist = ` `new` `int` `[V]; ` ` ` ` ` `// Step 1: Initialize distances from src ` ` ` `// to all other vertices as INFINITE ` ` ` `for` `(` `int` `i = ` `0` `; i < V; i++) ` ` ` `dist[i] = Integer.MAX_VALUE; ` ` ` `dist[src] = ` `0` `; ` ` ` ` ` `// Step 2: Relax all edges |V| - 1 times. ` ` ` `// A simple shortest path from src to any ` ` ` `// other vertex can have at-most |V| - 1 ` ` ` `// edges ` ` ` `for` `(` `int` `i = ` `1` `; i <= V - ` `1` `; i++) { ` ` ` `for` `(` `int` `j = ` `0` `; j < E; j++) { ` ` ` `int` `u = graph.edge[j].src; ` ` ` `int` `v = graph.edge[j].dest; ` ` ` `int` `weight = graph.edge[j].weight; ` ` ` `if` `(dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) ` ` ` `dist[v] = dist[u] + weight; ` ` ` `} ` ` ` `} ` ` ` ` ` `// Step 3: check for negative-weight cycles. ` ` ` `// The above step guarantees shortest distances ` ` ` `// if graph doesn't contain negative weight cycle. ` ` ` `// If we get a shorter path, then there ` ` ` `// is a cycle. ` ` ` `for` `(` `int` `i = ` `0` `; i < E; i++) { ` ` ` `int` `u = graph.edge[i].src; ` ` ` `int` `v = graph.edge[i].dest; ` ` ` `int` `weight = graph.edge[i].weight; ` ` ` `if` `(dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) ` ` ` `return` `true` `; ` ` ` `} ` ` ` ` ` `return` `false` `; ` ` ` `} ` ` ` ` ` `// Driver Code ` ` ` `public` `static` `void` `main(String[] args) { ` ` ` `int` `V = ` `5` `, E = ` `8` `; ` ` ` `Graph graph = createGraph(V, E); ` ` ` ` ` `// add edge 0-1 (or A-B in above figure) ` ` ` `graph.edge[` `0` `].src = ` `0` `; ` ` ` `graph.edge[` `0` `].dest = ` `1` `; ` ` ` `graph.edge[` `0` `].weight = -` `1` `; ` ` ` ` ` `// add edge 0-2 (or A-C in above figure) ` ` ` `graph.edge[` `1` `].src = ` `0` `; ` ` ` `graph.edge[` `1` `].dest = ` `2` `; ` ` ` `graph.edge[` `1` `].weight = ` `4` `; ` ` ` ` ` `// add edge 1-2 (or B-C in above figure) ` ` ` `graph.edge[` `2` `].src = ` `1` `; ` ` ` `graph.edge[` `2` `].dest = ` `2` `; ` ` ` `graph.edge[` `2` `].weight = ` `3` `; ` ` ` ` ` `// add edge 1-3 (or B-D in above figure) ` ` ` `graph.edge[` `3` `].src = ` `1` `; ` ` ` `graph.edge[` `3` `].dest = ` `3` `; ` ` ` `graph.edge[` `3` `].weight = ` `2` `; ` ` ` ` ` `// add edge 1-4 (or A-E in above figure) ` ` ` `graph.edge[` `4` `].src = ` `1` `; ` ` ` `graph.edge[` `4` `].dest = ` `4` `; ` ` ` `graph.edge[` `4` `].weight = ` `2` `; ` ` ` ` ` `// add edge 3-2 (or D-C in above figure) ` ` ` `graph.edge[` `5` `].src = ` `3` `; ` ` ` `graph.edge[` `5` `].dest = ` `2` `; ` ` ` `graph.edge[` `5` `].weight = ` `5` `; ` ` ` ` ` `// add edge 3-1 (or D-B in above figure) ` ` ` `graph.edge[` `6` `].src = ` `3` `; ` ` ` `graph.edge[` `6` `].dest = ` `1` `; ` ` ` `graph.edge[` `6` `].weight = ` `1` `; ` ` ` ` ` `// add edge 4-3 (or E-D in above figure) ` ` ` `graph.edge[` `7` `].src = ` `4` `; ` ` ` `graph.edge[` `7` `].dest = ` `3` `; ` ` ` `graph.edge[` `7` `].weight = -` `3` `; ` ` ` ` ` `if` `(isNegCycleBellmanFord(graph, ` `0` `)) ` ` ` `System.out.println(` `"Yes"` `); ` ` ` `else` ` ` `System.out.println(` `"No"` `); ` ` ` `} ` `} ` ` ` `// This code is contributed by ` `// sanjeev2552 ` |

*chevron_right*

*filter_none*

**Output :**

No

**How does it work?**

As discussed in Bellman Ford algorithm, for a given source, it first calculates the shortest distances which have at-most one edge in the path. Then, it calculates shortest paths with at-nost 2 edges, and so on. After the i-th iteration of outer loop, the shortest paths with at most i edges are calculated. There can be maximum |V| – 1 edges in any simple path, that is why the outer loop runs |v| – 1 times. If there is a negative weight cycle, then one more iteration would give a shorted path.

**How to handle disconnected graph (If cycle is not reachable from source)?**

The above algorithm and program might not work if the given graph is disconnected. It works when all vertices are reachable from source vertex 0.

To handle disconnected graph, we can repeat the process for vertices for which distance is infinite.

`// A C++ program for Bellman-Ford's single source ` `// shortest path algorithm. ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// a structure to represent a weighted edge in graph ` `struct` `Edge { ` ` ` `int` `src, dest, weight; ` `}; ` ` ` `// a structure to represent a connected, directed and ` `// weighted graph ` `struct` `Graph { ` ` ` `// V-> Number of vertices, E-> Number of edges ` ` ` `int` `V, E; ` ` ` ` ` `// graph is represented as an array of edges. ` ` ` `struct` `Edge* edge; ` `}; ` ` ` `// Creates a graph with V vertices and E edges ` `struct` `Graph* createGraph(` `int` `V, ` `int` `E) ` `{ ` ` ` `struct` `Graph* graph = ` `new` `Graph; ` ` ` `graph->V = V; ` ` ` `graph->E = E; ` ` ` `graph->edge = ` `new` `Edge[graph->E]; ` ` ` `return` `graph; ` `} ` ` ` `// The main function that finds shortest distances ` `// from src to all other vertices using Bellman- ` `// Ford algorithm. The function also detects ` `// negative weight cycle ` `bool` `isNegCycleBellmanFord(` `struct` `Graph* graph, ` ` ` `int` `src, ` `int` `dist[]) ` `{ ` ` ` `int` `V = graph->V; ` ` ` `int` `E = graph->E; ` ` ` ` ` `// Step 1: Initialize distances from src ` ` ` `// to all other vertices as INFINITE ` ` ` `for` `(` `int` `i = 0; i < V; i++) ` ` ` `dist[i] = INT_MAX; ` ` ` `dist[src] = 0; ` ` ` ` ` `// Step 2: Relax all edges |V| - 1 times. ` ` ` `// A simple shortest path from src to any ` ` ` `// other vertex can have at-most |V| - 1 ` ` ` `// edges ` ` ` `for` `(` `int` `i = 1; i <= V - 1; i++) { ` ` ` `for` `(` `int` `j = 0; j < E; j++) { ` ` ` `int` `u = graph->edge[j].src; ` ` ` `int` `v = graph->edge[j].dest; ` ` ` `int` `weight = graph->edge[j].weight; ` ` ` `if` `(dist[u] != INT_MAX && dist[u] + weight < dist[v]) ` ` ` `dist[v] = dist[u] + weight; ` ` ` `} ` ` ` `} ` ` ` ` ` `// Step 3: check for negative-weight cycles. ` ` ` `// The above step guarantees shortest distances ` ` ` `// if graph doesn't contain negative weight cycle. ` ` ` `// If we get a shorter path, then there ` ` ` `// is a cycle. ` ` ` `for` `(` `int` `i = 0; i < E; i++) { ` ` ` `int` `u = graph->edge[i].src; ` ` ` `int` `v = graph->edge[i].dest; ` ` ` `int` `weight = graph->edge[i].weight; ` ` ` `if` `(dist[u] != INT_MAX && dist[u] + weight < dist[v]) ` ` ` `return` `true` `; ` ` ` `} ` ` ` ` ` `return` `false` `; ` `} ` ` ` `// Returns true if given graph has negative weight ` `// cycle. ` `bool` `isNegCycleDisconnected(` `struct` `Graph* graph) ` `{ ` ` ` ` ` `int` `V = graph->V; ` ` ` `// To keep track of visited vertices to avoid ` ` ` `// recomputations. ` ` ` `bool` `visited[V]; ` ` ` `memset` `(visited, 0, ` `sizeof` `(visited)); ` ` ` ` ` `// This array is filled by Bellman-Ford ` ` ` `int` `dist[V]; ` ` ` ` ` `// Call Bellman-Ford for all those vertices ` ` ` `// that are not visited ` ` ` `for` `(` `int` `i = 0; i < V; i++) { ` ` ` `if` `(visited[i] == ` `false` `) { ` ` ` `// If cycle found ` ` ` `if` `(isNegCycleBellmanFord(graph, i, dist)) ` ` ` `return` `true` `; ` ` ` ` ` `// Mark all vertices that are visited ` ` ` `// in above call. ` ` ` `for` `(` `int` `i = 0; i < V; i++) ` ` ` `if` `(dist[i] != INT_MAX) ` ` ` `visited[i] = ` `true` `; ` ` ` `} ` ` ` `} ` ` ` ` ` `return` `false` `; ` `} ` ` ` `// Driver program to test above functions ` `int` `main() ` `{ ` ` ` `/* Let us create the graph given in above example */` ` ` `int` `V = 5; ` `// Number of vertices in graph ` ` ` `int` `E = 8; ` `// Number of edges in graph ` ` ` `struct` `Graph* graph = createGraph(V, E); ` ` ` ` ` `// add edge 0-1 (or A-B in above figure) ` ` ` `graph->edge[0].src = 0; ` ` ` `graph->edge[0].dest = 1; ` ` ` `graph->edge[0].weight = -1; ` ` ` ` ` `// add edge 0-2 (or A-C in above figure) ` ` ` `graph->edge[1].src = 0; ` ` ` `graph->edge[1].dest = 2; ` ` ` `graph->edge[1].weight = 4; ` ` ` ` ` `// add edge 1-2 (or B-C in above figure) ` ` ` `graph->edge[2].src = 1; ` ` ` `graph->edge[2].dest = 2; ` ` ` `graph->edge[2].weight = 3; ` ` ` ` ` `// add edge 1-3 (or B-D in above figure) ` ` ` `graph->edge[3].src = 1; ` ` ` `graph->edge[3].dest = 3; ` ` ` `graph->edge[3].weight = 2; ` ` ` ` ` `// add edge 1-4 (or A-E in above figure) ` ` ` `graph->edge[4].src = 1; ` ` ` `graph->edge[4].dest = 4; ` ` ` `graph->edge[4].weight = 2; ` ` ` ` ` `// add edge 3-2 (or D-C in above figure) ` ` ` `graph->edge[5].src = 3; ` ` ` `graph->edge[5].dest = 2; ` ` ` `graph->edge[5].weight = 5; ` ` ` ` ` `// add edge 3-1 (or D-B in above figure) ` ` ` `graph->edge[6].src = 3; ` ` ` `graph->edge[6].dest = 1; ` ` ` `graph->edge[6].weight = 1; ` ` ` ` ` `// add edge 4-3 (or E-D in above figure) ` ` ` `graph->edge[7].src = 4; ` ` ` `graph->edge[7].dest = 3; ` ` ` `graph->edge[7].weight = -3; ` ` ` ` ` `if` `(isNegCycleDisconnected(graph)) ` ` ` `cout << ` `"Yes"` `; ` ` ` `else` ` ` `cout << ` `"No"` `; ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

Output :

No

Detecting negative cycle using Floyd Warshall

This article is contributed by **kartik**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

## Recommended Posts:

- Detect cycle in the graph using degrees of nodes of graph
- Detect cycle in an undirected graph using BFS
- Detect Cycle in a Directed Graph using BFS
- Detect cycle in an undirected graph
- Detect Cycle in a Directed Graph
- Detect Cycle in a directed graph using colors
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Bellman–Ford Algorithm | DP-23
- Bellman Ford Algorithm (Simple Implementation)
- Detecting negative cycle using Floyd Warshall
- Coloring a Cycle Graph
- Degree of a Cycle Graph
- Check if there is a cycle with odd weight sum in an undirected graph
- Shortest cycle in an undirected unweighted graph
- Find minimum weight cycle in an undirected graph