Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Shortest Path in Directed Acyclic Graph
Next article icon

Johnson’s algorithm for All-pairs shortest paths

Last Updated : 03 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The problem is to find the shortest paths between every pair of vertices in a given weighted directed Graph and weights may be negative. We have discussed Floyd Warshall Algorithm for this problem.  The time complexity of the Floyd Warshall Algorithm is Θ(V3). 

Using Johnson’s algorithm, we can find all pair shortest paths in O(V2log V + VE) time. Johnson’s algorithm uses both Dijkstra and Bellman-Ford as subroutines. If we apply Dijkstra’s Single Source shortest path algorithm for every vertex, considering every vertex as the source, we can find all pair shortest paths in O(V*(V + E) * Log V) time. 

So using Dijkstra’s single-source shortest path seems to be a better option than Floyd Warshall’s Algorithm , but the problem with Dijkstra’s algorithm is, that it doesn’t work for negative weight edge. The idea of Johnson’s algorithm is to re-weight all edges and make them all positive, then apply Dijkstra’s algorithm for every vertex. 

How to transform a given graph into a graph with all non-negative weight edges? 

One may think of a simple approach of finding the minimum weight edge and adding this weight to all edges. Unfortunately, this doesn’t work as there may be a different number of edges in different paths (See this for an example). If there are multiple paths from a vertex u to v, then all paths must be increased by the same amount, so that the shortest path remains the shortest in the transformed graph. The idea of Johnson’s algorithm is to assign a weight to every vertex. Let the weight assigned to vertex u be h[u]. 

We reweight edges using vertex weights. For example, for an edge (u, v) of weight w(u, v), the new weight becomes w(u, v) + h[u] – h[v]. The great thing about this reweighting is, that all set of paths between any two vertices is increased by the same amount and all negative weights become non-negative. Consider any path between two vertices s and t, the weight of every path is increased by h[s] – h[t], and all h[] values of vertices on the path from s to t cancel each other. 

How do we calculate h[] values? 

Bellman-Ford algorithm is used for this purpose. Following is the complete algorithm. A new vertex is added to the graph and connected to all existing vertices. The shortest distance values from the new vertex to all existing vertices are h[] values. 

Algorithm: 

  1. Let the given graph be G. Add a new vertex s to the graph, add edges from the new vertex to all vertices of G. Let the modified graph be G’. 
  2. Run the Bellman-Ford algorithm on G’ with s as the source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s. 
  3. Reweight the edges of the original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”. 
  4. Remove the added vertex s and run Dijkstra’s algorithm for every vertex. 

How does the transformation ensure nonnegative weight edges? 

The following property is always true about h[] values as they are the shortest distances.

   h[v] <= h[u] + w(u, v) 

The property simply means that the shortest distance from s to v must be smaller than or equal to the shortest distance from s to u plus the weight of the edge (u, v). The new weights are w(u, v) + h[u] – h[v]. The value of the new weights must be greater than or equal to zero because of the inequality “h[v] <= h[u] + w(u, v)”. 

Example: Let us consider the following graph. 

Johnson1

 We add a source s and add edges from s to all vertices of the original graph. In the following diagram s is 4. 

 

Johnson2 

We calculate the shortest distances from 4 to all other vertices using Bellman-Ford algorithm. The shortest distances from 4 to 0, 1, 2 and 3 are 0, -5, -1 and 0 respectively, i.e., h[] = {0, -5, -1, 0}. Once we get these distances, we remove the source vertex 4 and reweight the edges using following formula. w(u, v) = w(u, v) + h[u] – h[v].

 Johnson3 

Since all weights are positive now, we can run Dijkstra’s shortest path algorithm for every vertex as the source. 

C++
#include <iostream> #include <vector> #include <limits> #include <algorithm>  #define INF std::numeric_limits<int>::max()  using namespace std;  // Function to find the vertex with the minimum distance // that has not yet been included in the shortest path tree int Min_Distance(const vector<int>& dist, const vector<bool>& visited) {     int min = INF, min_index;     for (int v = 0; v < dist.size(); ++v) {         if (!visited[v] && dist[v] <= min) {             min = dist[v];             min_index = v;         }     }     return min_index; }  // Function to perform Dijkstra's algorithm on the modified graph void Dijkstra_Algorithm(const vector<vector<int>>& graph, const vector<vector<int>>& altered_graph, int source) {     int V = graph.size();  // Number of vertices     vector<int> dist(V, INF);  // Distance from source to each vertex     vector<bool> visited(V, false);  // Track visited vertices          dist[source] = 0;  // Distance to source itself is 0      // Compute shortest path for all vertices     for (int count = 0; count < V - 1; ++count) {         // Select the vertex with the minimum distance that hasn't been visited         int u = Min_Distance(dist, visited);         visited[u] = true;  // Mark this vertex as visited          // Update the distance value of the adjacent vertices of the selected vertex         for (int v = 0; v < V; ++v) {             if (!visited[v] && graph[u][v] != 0 && dist[u] != INF && dist[u] + altered_graph[u][v] < dist[v]) {                 dist[v] = dist[u] + altered_graph[u][v];             }         }     }      // Print the shortest distances from the source     cout << "Shortest Distance from vertex " << source << ":\n";     for (int i = 0; i < V; ++i) {         cout << "Vertex " << i << ": " << (dist[i] == INF ? "INF" : to_string(dist[i])) << endl;     } }  // Function to perform Bellman-Ford algorithm to find shortest distances // from a source vertex to all other vertices vector<int> BellmanFord_Algorithm(const vector<vector<int>>& edges, int V) {     vector<int> dist(V + 1, INF);  // Distance from source to each vertex     dist[V] = 0;  // Distance to the new source vertex (added vertex) is 0      // Add a new source vertex to the graph and connect it to all original vertices with 0 weight edges     vector<vector<int>> edges_with_extra(edges);     for (int i = 0; i < V; ++i) {         edges_with_extra.push_back({V, i, 0});     }      // Relax all edges |V| - 1 times     for (int i = 0; i < V; ++i) {         for (const auto& edge : edges_with_extra) {             if (dist[edge[0]] != INF && dist[edge[0]] + edge[2] < dist[edge[1]]) {                 dist[edge[1]] = dist[edge[0]] + edge[2];             }         }     }     return vector<int>(dist.begin(), dist.begin() + V);  // Return distances excluding the new source vertex }  // Function to implement Johnson's Algorithm void JohnsonAlgorithm(const vector<vector<int>>& graph) {     int V = graph.size();  // Number of vertices     vector<vector<int>> edges;          // Collect all edges from the graph     for (int i = 0; i < V; ++i) {         for (int j = 0; j < V; ++j) {             if (graph[i][j] != 0) {                 edges.push_back({i, j, graph[i][j]});             }         }     }      // Get the modified weights from Bellman-Ford algorithm     vector<int> altered_weights = BellmanFord_Algorithm(edges, V);     vector<vector<int>> altered_graph(V, vector<int>(V, 0));      // Modify the weights of the edges to remove negative weights     for (int i = 0; i < V; ++i) {         for (int j = 0; j < V; ++j) {             if (graph[i][j] != 0) {                 altered_graph[i][j] = graph[i][j] + altered_weights[i] - altered_weights[j];             }         }     }      // Print the modified graph with re-weighted edges     cout << "Modified Graph:\n";     for (const auto& row : altered_graph) {         for (int weight : row) {             cout << weight << ' ';         }         cout << endl;     }      // Run Dijkstra's algorithm for every vertex as the source     for (int source = 0; source < V; ++source) {         cout << "\nShortest Distance with vertex " << source << " as the source:\n";         Dijkstra_Algorithm(graph, altered_graph, source);     } }  // Main function to test the Johnson's Algorithm implementation int main() {     // Define a graph with possible negative weights     vector<vector<int>> graph = {         {0, -5, 2, 3},         {0, 0, 4, 0},         {0, 0, 0, 1},         {0, 0, 0, 0}     };      // Execute Johnson's Algorithm     JohnsonAlgorithm(graph);     return 0; } 
Java
import java.util.Arrays;  public class GFG {      // Define infinity as a large integer value     private static final int INF = Integer.MAX_VALUE;      // Function to find the vertex with the minimum distance     // from the source that has not yet been included in the shortest path tree     private static int minDistance(int[] dist, boolean[] sptSet) {         int min = INF, minIndex = 0;         for (int v = 0; v < dist.length; v++) {             // Update minIndex if a smaller distance is found             if (!sptSet[v] && dist[v] <= min) {                 min = dist[v];                 minIndex = v;             }         }         return minIndex;     }      // Function to perform Dijkstra's algorithm on the modified graph     private static void dijkstraAlgorithm(int[][] graph, int[][] alteredGraph, int source) {         int V = graph.length;  // Number of vertices         int[] dist = new int[V];  // Distance array to store shortest distance from source         boolean[] sptSet = new boolean[V];  // Boolean array to track visited vertices          // Initialize distances with infinity and source distance as 0         Arrays.fill(dist, INF);         dist[source] = 0;          // Compute shortest path for all vertices         for (int count = 0; count < V - 1; count++) {             // Pick the vertex with the minimum distance that hasn't been visited             int u = minDistance(dist, sptSet);             sptSet[u] = true;  // Mark this vertex as visited              // Update distance values for adjacent vertices             for (int v = 0; v < V; v++) {                 // Check for updates to the distance value                 if (!sptSet[v] && graph[u][v] != 0 && dist[u] != INF && dist[u] + alteredGraph[u][v] < dist[v]) {                     dist[v] = dist[u] + alteredGraph[u][v];                 }             }         }          // Print the shortest distances from the source vertex         System.out.println("Shortest Distance from vertex " + source + ":");         for (int i = 0; i < V; i++) {             System.out.println("Vertex " + i + ": " + (dist[i] == INF ? "INF" : dist[i]));         }     }      // Function to perform Bellman-Ford algorithm to calculate shortest distances     // from a source vertex to all other vertices     private static int[] bellmanFordAlgorithm(int[][] edges, int V) {         int[] dist = new int[V + 1];  // Distance array with an extra vertex         Arrays.fill(dist, INF);         dist[V] = 0;  // Distance to the new source vertex (added vertex) is 0          // Add edges from the new source vertex to all original vertices         int[][] edgesWithExtra = Arrays.copyOf(edges, edges.length + V);         for (int i = 0; i < V; i++) {             edgesWithExtra[edges.length + i] = new int[]{V, i, 0};         }          // Relax all edges |V| - 1 times         for (int i = 0; i < V; i++) {             for (int[] edge : edgesWithExtra) {                 if (dist[edge[0]] != INF && dist[edge[0]] + edge[2] < dist[edge[1]]) {                     dist[edge[1]] = dist[edge[0]] + edge[2];                 }             }         }          return Arrays.copyOf(dist, V);  // Return distances excluding the new source vertex     }      // Function to implement Johnson's Algorithm     private static void johnsonAlgorithm(int[][] graph) {         int V = graph.length;  // Number of vertices         int[][] edges = new int[V * (V - 1) / 2][3];  // Array to store edges         int index = 0;          // Collect all edges from the graph         for (int i = 0; i < V; i++) {             for (int j = 0; j < V; j++) {                 if (graph[i][j] != 0) {                     edges[index++] = new int[]{i, j, graph[i][j]};                 }             }         }          // Get the modified weights to remove negative weights using Bellman-Ford         int[] alteredWeights = bellmanFordAlgorithm(edges, V);         int[][] alteredGraph = new int[V][V];          // Modify the weights of the edges to ensure all weights are non-negative         for (int i = 0; i < V; i++) {             for (int j = 0; j < V; j++) {                 if (graph[i][j] != 0) {                     alteredGraph[i][j] = graph[i][j] + alteredWeights[i] - alteredWeights[j];                 }             }         }          // Print the modified graph with re-weighted edges         System.out.println("Modified Graph:");         for (int[] row : alteredGraph) {             for (int weight : row) {                 System.out.print(weight + " ");             }             System.out.println();         }          // Run Dijkstra's algorithm for each vertex as the source         for (int source = 0; source < V; source++) {             System.out.println("\nShortest Distance with vertex " + source + " as the source:");             dijkstraAlgorithm(graph, alteredGraph, source);         }     }      // Main function to test Johnson's Algorithm     public static void main(String[] args) {         // Define a graph with possible negative weights         int[][] graph = {             {0, -5, 2, 3},             {0, 0, 4, 0},             {0, 0, 0, 1},             {0, 0, 0, 0}         };          // Execute Johnson's Algorithm         johnsonAlgorithm(graph);     } } 
Python
# Implementation of Johnson's algorithm in Python3  # Import function to initialize the dictionary from collections import defaultdict INT_MAX = float('Inf')  # Function that returns the vertex  # with minimum distance  # from the source def Min_Distance(dist, visit):      (minimum, Minimum_Vertex) = (INT_MAX, 0)     for vertex in range(len(dist)):         if minimum > dist[vertex] and visit[vertex] == False:             (minimum, minVertex) = (dist[vertex], vertex)      return Minimum_Vertex   # Dijkstra Algorithm for Modified # Graph (After removing the negative weights) def Dijkstra_Algorithm(graph, Altered_Graph, source):      # Number of vertices in the graph     tot_vertices = len(graph)      # Dictionary to check if given vertex is     # already included in the shortest path tree     sptSet = defaultdict(lambda : False)      # Shortest distance of all vertices from the source     dist = [INT_MAX] * tot_vertices      dist[source] = 0      for count in range(tot_vertices):          # The current vertex which is at min Distance         # from the source and not yet included in the         # shortest path tree         curVertex = Min_Distance(dist, sptSet)         sptSet[curVertex] = True          for vertex in range(tot_vertices):             if ((sptSet[vertex] == False) and                 (dist[vertex] > (dist[curVertex] +                 Altered_Graph[curVertex][vertex])) and                 (graph[curVertex][vertex] != 0)):                                                                                       dist[vertex] = (dist[curVertex] +Altered_Graph[curVertex][vertex])      # Print the Shortest distance from the source     for vertex in range(tot_vertices):         print ('Vertex ' + str(vertex) + ': ' + str(dist[vertex]))  # Function to calculate shortest distances from source # to all other vertices using Bellman-Ford algorithm def BellmanFord_Algorithm(edges, graph, tot_vertices):      # Add a source s and calculate its min     # distance from every other node     dist = [INT_MAX] * (tot_vertices + 1)     dist[tot_vertices] = 0      for i in range(tot_vertices):         edges.append([tot_vertices, i, 0])      for i in range(tot_vertices):         for (source, destn, weight) in edges:             if((dist[source] != INT_MAX) and                     (dist[source] + weight < dist[destn])):                 dist[destn] = dist[source] + weight      # Don't send the value for the source added     return dist[0:tot_vertices]  # Function to implement Johnson Algorithm def JohnsonAlgorithm(graph):      edges = []      # Create a list of edges for Bellman-Ford Algorithm     for i in range(len(graph)):         for j in range(len(graph[i])):              if graph[i][j] != 0:                 edges.append([i, j, graph[i][j]])      # Weights used to modify the original weights     Alter_weigts = BellmanFord_Algorithm(edges, graph, len(graph))      Altered_Graph = [[0 for p in range(len(graph))] for q in                     range(len(graph))]      # Modify the weights to get rid of negative weights     for i in range(len(graph)):         for j in range(len(graph[i])):              if graph[i][j] != 0:                 Altered_Graph[i][j] = (graph[i][j] +                         Alter_weigts[i] - Alter_weigts[j]);      print ('Modified Graph: ' + str(Altered_Graph))      # Run Dijkstra for every vertex as source one by one     for source in range(len(graph)):         print ('\nShortest Distance with vertex ' +                         str(source) + ' as the source:\n')         Dijkstra_Algorithm(graph, Altered_Graph, source)  # Driver Code graph = [[0, -5, 2, 3],         [0, 0, 4, 0],         [0, 0, 0, 1],         [0, 0, 0, 0]]  JohnsonAlgorithm(graph) 
JavaScript
const INF = Number.MAX_VALUE;  // Function to find the vertex with minimum distance from the source function minDistance(dist, visited) {     let min = INF;     let minIndex = -1;      for (let v = 0; v < dist.length; v++) {         if (!visited[v] && dist[v] < min) {             min = dist[v];             minIndex = v;         }     }     return minIndex; }  // Function to perform Dijkstra's algorithm on the modified graph function dijkstraAlgorithm(graph, alteredGraph, source) {     const V = graph.length;     const dist = Array(V).fill(INF);     const visited = Array(V).fill(false);      dist[source] = 0;      for (let count = 0; count < V - 1; count++) {         const u = minDistance(dist, visited);         visited[u] = true;          for (let v = 0; v < V; v++) {             if (!visited[v] && graph[u][v] !== 0 && dist[u] !== INF && dist[u] + alteredGraph[u][v] < dist[v]) {                 dist[v] = dist[u] + alteredGraph[u][v];             }         }     }      console.log(`Shortest Distance from vertex ${source}:`);     for (let i = 0; i < V; i++) {         console.log(`Vertex ${i}: ${dist[i] === INF ? "INF" : dist[i]}`);     } }  // Function to perform Bellman-Ford algorithm to calculate shortest distances function bellmanFordAlgorithm(edges, V) {     const dist = Array(V + 1).fill(INF);     dist[V] = 0;      const edgesWithExtra = edges.slice();     for (let i = 0; i < V; i++) {         edgesWithExtra.push([V, i, 0]);     }      for (let i = 0; i < V; i++) {         for (const [src, dest, weight] of edgesWithExtra) {             if (dist[src] !== INF && dist[src] + weight < dist[dest]) {                 dist[dest] = dist[src] + weight;             }         }     }      return dist.slice(0, V); }  // Function to implement Johnson's Algorithm function johnsonAlgorithm(graph) {     const V = graph.length;     const edges = [];      for (let i = 0; i < V; i++) {         for (let j = 0; j < V; j++) {             if (graph[i][j] !== 0) {                 edges.push([i, j, graph[i][j]]);             }         }     }      const alteredWeights = bellmanFordAlgorithm(edges, V);     const alteredGraph = Array.from({ length: V }, () => Array(V).fill(0));      for (let i = 0; i < V; i++) {         for (let j = 0; j < V; j++) {             if (graph[i][j] !== 0) {                 alteredGraph[i][j] = graph[i][j] + alteredWeights[i] - alteredWeights[j];             }         }     }      console.log("Modified Graph:");     alteredGraph.forEach(row => {         console.log(row.join(' '));     });      for (let source = 0; source < V; source++) {         console.log(`\nShortest Distance with vertex ${source} as the source:`);         dijkstraAlgorithm(graph, alteredGraph, source);     } }  // Driver Code const graph = [     [0, -5, 2, 3],     [0, 0, 4, 0],     [0, 0, 0, 1],     [0, 0, 0, 0] ];  johnsonAlgorithm(graph); 

Output
Following matrix shows the shortest distances between every pair of vertices        0      5      8      9     INF      0      3      4     INF    INF      0      1     INF    INF    INF      0 

Time Complexity: The main steps in the algorithm are Bellman-Ford Algorithm called once and Dijkstra called V times. Time complexity of Bellman Ford is O(VE) and time complexity of Dijkstra is O((V + E)Log V). So overall time complexity is O(V2log V + VE). 

The time complexity of Johnson’s algorithm becomes the same as Floyd Warshall’s Algorithm when the graph is complete (For a complete graph E = O(V2). But for sparse graphs, the algorithm performs much better than Floyd Warshall’s Algorithm.

Auxiliary Space: O(V2)



Next Article
Shortest Path in Directed Acyclic Graph
author
kartik
Improve
Article Tags :
  • DSA
  • Graph
  • Shortest Path
Practice Tags :
  • Graph
  • 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
      Given a directed Graph, the task is to perform Depth First Search of the given graph. Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list. Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pic
      10 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

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences