Given a weighted graph with V vertices and E edges, along with a source vertex src
, the task is to compute the shortest distances from the source to all other vertices. If a vertex is unreachable from the source, its distance should be marked as 108. In the presence of a negative weight cycle, return -1 to signify that shortest path calculations are not feasible.
Examples:
Input: V = 5, edges = [[0, 1, 5], [1, 2, 1], [1, 3, 2], [2, 4, 1], [4, 3, -1]], src = 0

Output: [0, 5, 6, 6, 7]
Explanation: Shortest Paths:
For 0 to 1 minimum distance will be 5. By following path 0 → 1
For 0 to 2 minimum distance will be 6. By following path 0 → 1 → 2
For 0 to 3 minimum distance will be 6. By following path 0 → 1 → 2 → 4 → 3
For 0 to 4 minimum distance will be 7. By following path 0 → 1 → 2 → 4
Input: V = 4, edges = [[0, 1, 4], [1, 2, -6], [2, 3, 5], [3, 1, -2]], src = 0

Output: [-1]
Explanation: The graph contains a negative weight cycle formed by the path 1 → 2 → 3 → 1, where the total weight of the cycle is negative.
Approach: Bellman-Ford Algorithm – O(V*E) Time and O(V) Space
Negative weight cycle:
A negative weight cycle is a cycle in a graph, whose sum of edge weights is negative. If you traverse the cycle, the total weight accumulated would be less than zero.

In the presence of negative weight cycle in the graph, the shortest path doesn’t exist because with each traversal of the cycle shortest path keeps decreasing.
Limitation of Dijkstra’s Algorithm:
Since, we need to find the single source shortest path, we might initially think of using Dijkstra’s algorithm. However, Dijkstra is not suitable when the graph consists of negative edges. The reason is, it doesn’t revisit those nodes which have already been marked as visited. If a shorter path exists through a longer route with negative edges, Dijkstra’s algorithm will fail to handle it.
Principle of Relaxation of Edges
- Relaxation means updating the shortest distance to a node if a shorter path is found through another node. For an edge (u, v) with weight w:
- If going through u gives a shorter path to v from the source node (i.e., distance[v] > distance[u] + w), we update the distance[v] as distance[u] + w.
- In the bellman-ford algorithm, this process is repeated (V – 1) times for all the edges.
Why Relaxing Edges (V – 1) times gives us Single Source Shortest Path?
A shortest path between two vertices can have at most (V – 1) edges. It is not possible to have a simple path with more than (V – 1) edges (otherwise it would form a cycle). Therefore, repeating the relaxation process (V – 1) times ensures that all possible paths between source and any other node have been covered.
Assuming node 0 as the source vertex, let’s see how we can relax the edges to find the shortest paths:

- In the first relaxation, since the shortest paths for vertices 1 and 2 are unknown (infinite, i.e., 108), the shortest paths for vertices 2 and 3 will also remain infinite (108)
. And, for vertex 1, the distance will be updated to 4, as dist[0] + 4 < dist[1]
(i.e., 0 + 4 <
108). - In the second relaxation, the shortest path for vertex 2 is still infinite (e.g. 108), which means the shortest path for vertex 3 will also remain infinite. For vertex 2, the distance can be updated to 3, as dist[1] + (-1) = 3.
- In the third relaxation, the shortest path for vertex 3 will be updated to 5, as dist[2] + 2 = 5.
So, in above example, dist[1] is updated in 1st relaxation, dist[2] is updated in second relaxation, so the dist for the last node (V – 1), will be updated in (V – 1) th relaxation.
Detection of a Negative Weight Cycle
- As we have discussed earlier that, we need (V – 1) relaxations of all the edges to achieve single source shortest path. If one additional relaxation (Vth) for any edge is possible, it indicates that some edges with overall negative weight has been traversed once more. This indicates the presence of a negative weight cycle in the graph.
Bellman-Ford is a single source shortest path algorithm. It effectively works in the cases of negative edges and is able to detect negative cycles as well. It works on the principle of relaxation of the edges.
Illustration:
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> bellmanFord(int V, vector<vector<int>>& edges, int src) {
// Initially distance from source to all
// other vertices is not known(Infinite).
vector<int> dist(V, 1e8);
dist[src] = 0;
// Relaxation of all the edges V times, not (V - 1) as we
// need one additional relaxation to detect negative cycle
for (int i = 0; i < V; i++) {
for (vector<int> edge : edges) {
int u = edge[0];
int v = edge[1];
int wt = edge[2];
if (dist[u] != 1e8 && dist[u] + wt < dist[v]) {
// If this is the Vth relaxation, then there is
// a negative cycle
if(i == V - 1)
return {-1};
// Update shortest distance to node v
dist[v] = dist[u] + wt;
}
}
}
return dist;
}
int main() {
// Number of vertices in the graph
int V = 5;
// Edge list representation: {source, destination, weight}
vector<vector<int>> edges = {
{1, 3, 2},
{4, 3, -1},
{2, 4, 1},
{1, 2, 1},
{0, 1, 5}
};
// Define the source vertex
int src = 0;
// Run Bellman-Ford algorithm to get shortest paths from src
vector<int> ans = bellmanFord(V, edges, src);
// Output the shortest distances from src to all vertices
for (int dist : ans)
cout << dist << " ";
return 0;
}
Java
import java.util.Arrays;
class GfG {
static int[] bellmanFord(int V, int[][] edges, int src) {
// Initially distance from source to all other vertices
// is not known(Infinite).
int[] dist = new int[V];
Arrays.fill(dist, (int)1e8);
dist[src] = 0;
// Relaxation of all the edges V times, not (V - 1) as we
// need one additional relaxation to detect negative cycle
for (int i = 0; i < V; i++) {
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
int wt = edge[2];
if (dist[u] != 1e8 && dist[u] + wt < dist[v]) {
// If this is the Vth relaxation, then there is
// a negative cycle
if (i == V - 1)
return new int[]{-1};
// Update shortest distance to node v
dist[v] = dist[u] + wt;
}
}
}
return dist;
}
public static void main(String[] args) {
// Number of vertices in the graph
int V = 5;
// Edge list representation: {source, destination, weight}
int[][] edges = new int[][] {
{1, 3, 2},
{4, 3, -1},
{2, 4, 1},
{1, 2, 1},
{0, 1, 5}
};
// Source vertex for Bellman-Ford algorithm
int src = 0;
// Run Bellman-Ford algorithm from the source vertex
int[] ans = bellmanFord(V, edges, src);
// Print shortest distances from the source to all vertices
for (int dist : ans)
System.out.print(dist + " ");
}
}
Python
def bellmanFord(V, edges, src):
# Initially distance from source to all other vertices
# is not known(Infinite) e.g. 1e8.
dist = [100000000] * V
dist[src] = 0
# Relaxation of all the edges V times, not (V - 1) as we
# need one additional relaxation to detect negative cycle
for i in range(V):
for edge in edges:
u, v, wt = edge
if dist[u] != 100000000 and dist[u] + wt < dist[v]:
# If this is the Vth relaxation, then there
# is a negative cycle
if i == V - 1:
return [-1]
# Update shortest distance to node v
dist[v] = dist[u] + wt
return dist
if __name__ == '__main__':
V = 5
edges = [[1, 3, 2], [4, 3, -1], [2, 4, 1], [1, 2, 1], [0, 1, 5]]
src = 0
ans = bellmanFord(V, edges, src)
print(' '.join(map(str, ans)))
C#
using System;
class GfG {
// Function to perform the Bellman-Ford algorithm
static int[] bellmanFord(int V, int[,] edges, int src) {
// Initialize distances from source to all
// vertices as "infinity" (represented by 1e8)
int[] dist = new int[V];
for (int i = 0; i < V; i++)
dist[i] = (int)1e8;
// Distance to the source is always 0
dist[src] = 0;
// Get the number of edges from the 2D edge array
int E = edges.GetLength(0);
// Relax all edges V times
// The extra iteration (V-th) is used to detect a
// negative weight cycle
for (int i = 0; i < V; i++) {
for (int j = 0; j < E; j++) {
// Extract edge info: from u to v with weight wt
int u = edges[j, 0];
int v = edges[j, 1];
int wt = edges[j, 2];
// Only proceed if u has already been reached
// (i.e., not infinity)
if (dist[u] != (int)1e8 && dist[u] + wt < dist[v]) {
// If this is the V-th iteration and relaxation is still
// possible, it means there is a negative weight cycle
if (i == V - 1)
// Indicate presence of negative cycle
return new int[] { -1 };
// Update the distance to vertex v through vertex u
dist[v] = dist[u] + wt;
}
}
}
// Return the final shortest distances
return dist;
}
static void Main() {
// Number of vertices in the graph
int V = 5;
// Edge list: each row represents {source, destination, weight}
int[,] edges = {
{ 1, 3, 2 },
{ 4, 3, -1 },
{ 2, 4, 1 },
{ 1, 2, 1 },
{ 0, 1, 5 }
};
// Source vertex
int src = 0;
// Call Bellman-Ford and store the result
int[] ans = bellmanFord(V, edges, src);
// Print the shortest distances from source to all vertices
foreach (int d in ans)
Console.Write(d + " ");
}
}
JavaScript
function bellmanFord(V, edges, src) {
// Initially distance from source to all
// other vertices is not known(Infinite).
let dist = new Array(V).fill(1e8);
dist[src] = 0;
// Relaxation of all the edges V times, not (V - 1) as we
// need one additional relaxation to detect negative cycle
for (let i = 0; i < V; i++) {
for (let edge of edges) {
let u = edge[0];
let v = edge[1];
let wt = edge[2];
if (dist[u] !== 1e8 && dist[u] + wt < dist[v]) {
// If this is the Vth relaxation, then there is
// a negative cycle
if (i === V - 1)
return [-1];
// Update shortest distance to node v
dist[v] = dist[u] + wt;
}
}
}
return dist;
}
// Driver Code
let V = 5;
let edges = [
[1, 3, 2],
[4, 3, -1],
[2, 4, 1],
[1, 2, 1],
[0, 1, 5]
];
let src = 0;
let ans = bellmanFord(V, edges, src);
console.log(ans.join(" "));
Problems based on Shortest Path
Similar Reads
Graph Algorithms
Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
3 min read
Introduction to Graph Data Structure
Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
15+ min read
Graph and its representations
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
12 min read
Types of Graphs with Examples
A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
9 min read
Basic Properties of a Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
4 min read
Applications, Advantages and Disadvantages of Graph
Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
7 min read
Transpose graph
Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
9 min read
Difference Between Graph and Tree
Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
2 min read
BFS and DFS on Graph
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Depth First Search or DFS for a Graph
In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
13 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
4 min read
Iterative Depth First Traversal of Graph
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0
15+ min read
BFS for Disconnected Graph
In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
14 min read
Transitive Closure of a Graph using DFS
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
8 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
2 min read
Cycle in a Graph
Detect Cycle in a Directed Graph
Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not. Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 0 Input: V = 4, edges[][] = [[0, 1], [0, 2
15+ min read
Detect cycle in an undirected graph
Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 1 â 0 Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: falseExplana
8 min read
Detect Cycle in a directed graph using colors
Given a directed graph represented by the number of vertices V and a list of directed edges, determine whether the graph contains a cycle. Your task is to implement a function that accepts V (number of vertices) and edges (an array of directed edges where each edge is a pair [u, v]), and returns tru
9 min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
15+ min read
Cycles of length n in an undirected and connected graph
Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
10 min read
Detecting negative cycle using Floyd Warshall
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 adva
12 min read
Clone a Directed Acyclic Graph
A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
12 min read