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:
Count all possible walks from a source to a destination with exactly k edges
Next article icon

Strongly Connected Components

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Strongly Connected Components (SCCs) are a fundamental concept in graph theory and algorithms. In a directed graph, a Strongly Connected Component is a subset of vertices where every vertex in the subset is reachable from every other vertex in the same subset by traversing the directed edges. Finding the SCCs of a graph can provide important insights into the structure and connectivity of the graph, with applications in various fields such as social network analysis, web crawling, and network routing. This tutorial will explore the definition, properties, and efficient algorithms for identifying Strongly Connected Components in graph data structures

Table of Content

  • What is Strongly Connected Components (SCCs)?
  • Why Strongly Connected Components (SCCs) are Important?
  • Difference Between Connected and Strongly Connected Components (SCCs)
  • Why conventional DFS method cannot be used to find strongly connected components?
  • Connecting Two Strongly Connected Component by a Unidirectional Edge
  • Brute Force Approach for Finding Strongly Connected Components
  • Efficient Approach for Finding Strongly Connected Components (SCCs)
    • 1. Kosaraju’s Algorithm:
    • 2. Tarjan’s Algorithm:
  • Conclusion

What is Strongly Connected Components (SCCs)?

A strongly connected component of a directed graph is a maximal subgraph where every pair of vertices is mutually reachable. This means that for any two nodes A and B in this subgraph, there is a path from A to B and a path from B to A.

For example: The below graph has two strongly connected components {1,2,3,4} and {5,6,7} since there is path from each vertex to every other vertex in the same strongly connected component. 

scc_fianldrawio

Strongly Connected Component

Why Strongly Connected Components (SCCs) are Important?

Understanding SCCs is crucial for various applications such as:

  • Network Analysis: Identifying clusters of tightly interconnected nodes.
  • Optimizing Web Crawlers: Determining parts of the web graph that are closely linked.
  • Dependency Resolution: In software, understanding which modules are interdependent.

Difference Between Connected and Strongly Connected Components (SCCs)

Connectivity in a undirected graph refers to whether two vertices are reachable from each other or not. Two vertices are said to be connected if there is path between them. Meanwhile Strongly Connected is applicable only to directed graphs. A subgraph of a directed graph is considered to be an Strongly Connected Components (SCC) if and only if for every pair of vertices A and B, there exists a path from A to B and a path from B to A. Let’s see why the standard dfs method to find connnected components in a graph cannot be used to determine strongly connected components.

Consider the following graph:

scc_fianldrawio

Now, let’s start a dfs call from vertex 1 to visit other vertices.

dfs_finaldrawio

Why conventional DFS method cannot be used to find the strongly connected components?

All the vertices can be reached from vertex 1. But vertices 1 and 5,6,7 can not be in the same strongly connected component because there is no directed path from vertex 5,6 or 7 to vertex 1. The graph has two strongly connected components {1,2,3,4} and {5,6,7}. So the conventional dfs method cannot be used to find the strongly connected components.

Connecting Two Strongly Connected Component by a Unidirectional Edge

Two different connected components becomes a single component if a edge is added between a vertex from one component to a vertex of other component. But this is not the case in strongly connected components. Two strongly connected components doesn’t become a single strongly connected component if there is only a unidirectional edge from one SCC to other SCC.

unidrawio-(2)

Brute Force Approach for Finding Strongly Connected Components

The simple method will be for each vertex i (which is not a part of any strongly component) find the vertices which will be the part of strongly connected component containing vertex i. Two vertex i and j will be in the same strongly connected component if they there is a directed path from vertex i to vertex j and vice-versa.

Let’s understand the approach with the help of following example:

exampledrawio

  • Starting with vertex 1. There is path from vertex 1 to vertex 2 and vice-versa. Similarly there is a path from vertex 1 to vertex 3 and vice versa. So, vertex 2 and 3 will be in the same Strongly Connected Component as vertex 1. Although there is directed path form vertex 1 to vertex 4 and vertex 5. But there is no directed path from vertex 4,5 to vertex 1 so vertex 4 and 5 won’t be in the same Strongly Connected Component as vertex 1. Thus Vertex 1,2 and 3 forms a Strongly Connected Component.
  • For Vertex 2 and 3, there Strongly Connected Component has already been determined.
  • For Vertex 4, there is a path from vertex 4 to vertex 5 but there is no path from vertex 5 to vertex 4. So vertex 4 and 5 won’t be in the Same Strongly Connected Component. So both Vertex 4 and Vertex 5 will be part of Single Strongly Connected Component.
  • Hence there will be 3 Strongly Connected Component {1,2,3}, {4} and {5}.

Below is the implementation of above approach:

C++
#include <bits/stdc++.h> using namespace std;  class GFG { public:     // dfs Function to reach destination     bool dfs(int curr, int des, vector<vector<int> >& adj,              vector<int>& vis)     {          // If curr node is destination return true         if (curr == des) {             return true;         }         vis[curr] = 1;         for (auto x : adj[curr]) {             if (!vis[x]) {                 if (dfs(x, des, adj, vis)) {                     return true;                 }             }         }         return false;     }      // To tell whether there is path from source to     // destination     bool isPath(int src, int des, vector<vector<int> >& adj)     {         vector<int> vis(adj.size() + 1, 0);         return dfs(src, des, adj, vis);     }      // Function to return all the strongly connected     // component of a graph.     vector<vector<int> > findSCC(int n,                                  vector<vector<int> >& a)     {         // Stores all the strongly connected components.         vector<vector<int> > ans;          // Stores whether a vertex is a part of any Strongly         // Connected Component         vector<int> is_scc(n + 1, 0);          vector<vector<int> > adj(n + 1);          for (int i = 0; i < a.size(); i++) {             adj[a[i][0]].push_back(a[i][1]);         }          // Traversing all the vertices         for (int i = 1; i <= n; i++) {              if (!is_scc[i]) {                  // If a vertex i is not a part of any SCC                 // insert it into a new SCC list and check                 // for other vertices whether they can be                 // thr part of thidl ist.                 vector<int> scc;                 scc.push_back(i);                  for (int j = i + 1; j <= n; j++) {                      // If there is a path from vertex i to                     // vertex j and vice versa put vertex j                     // into the current SCC list.                     if (!is_scc[j] && isPath(i, j, adj)                         && isPath(j, i, adj)) {                         is_scc[j] = 1;                         scc.push_back(j);                     }                 }                  // Insert the SCC containing vertex i into                 // the final list.                 ans.push_back(scc);             }         }         return ans;     } };  // Driver Code Starts  int main() {      GFG obj;     int V = 5;     vector<vector<int> > edges{         { 1, 3 }, { 1, 4 }, { 2, 1 }, { 3, 2 }, { 4, 5 }     };     vector<vector<int> > ans = obj.findSCC(V, edges);     cout << "Strongly Connected Components are:\n";     for (auto x : ans) {         for (auto y : x) {             cout << y << " ";         }         cout << "\n";     } } 
Java
import java.util.ArrayList; import java.util.List;  class GFG {      // dfs Function to reach destination     boolean dfs(int curr, int des, List<List<Integer>> adj,                 List<Integer> vis) {          // If curr node is destination return true         if (curr == des) {             return true;         }         vis.set(curr, 1);         for (int x : adj.get(curr)) {             if (vis.get(x) == 0) {                 if (dfs(x, des, adj, vis)) {                     return true;                 }             }         }         return false;     }      // To tell whether there is path from source to     // destination     boolean isPath(int src, int des, List<List<Integer>> adj) {         List<Integer> vis = new ArrayList<>(adj.size() + 1);         for (int i = 0; i <= adj.size(); i++) {             vis.add(0);         }         return dfs(src, des, adj, vis);     }      // Function to return all the strongly connected     // component of a graph.     List<List<Integer>> findSCC(int n, List<List<Integer>> a) {         // Stores all the strongly connected components.         List<List<Integer>> ans = new ArrayList<>();          // Stores whether a vertex is a part of any Strongly         // Connected Component         List<Integer> is_scc = new ArrayList<>(n + 1);         for (int i = 0; i <= n; i++) {             is_scc.add(0);         }          List<List<Integer>> adj = new ArrayList<>();         for (int i = 0; i <= n; i++) {             adj.add(new ArrayList<>());         }          for (List<Integer> edge : a) {             adj.get(edge.get(0)).add(edge.get(1));         }          // Traversing all the vertices         for (int i = 1; i <= n; i++) {              if (is_scc.get(i) == 0) {                  // If a vertex i is not a part of any SCC                 // insert it into a new SCC list and check                 // for other vertices whether they can be                 // the part of this list.                 List<Integer> scc = new ArrayList<>();                 scc.add(i);                  for (int j = i + 1; j <= n; j++) {                      // If there is a path from vertex i to                     // vertex j and vice versa, put vertex j                     // into the current SCC list.                     if (is_scc.get(j) == 0 && isPath(i, j, adj)                             && isPath(j, i, adj)) {                         is_scc.set(j, 1);                         scc.add(j);                     }                 }                  // Insert the SCC containing vertex i into                 // the final list.                 ans.add(scc);             }         }         return ans;     } }  public class Main {      public static void main(String[] args) {          GFG obj = new GFG();         int V = 5;         List<List<Integer>> edges = new ArrayList<>();         edges.add(new ArrayList<>(List.of(1, 3)));         edges.add(new ArrayList<>(List.of(1, 4)));         edges.add(new ArrayList<>(List.of(2, 1)));         edges.add(new ArrayList<>(List.of(3, 2)));         edges.add(new ArrayList<>(List.of(4, 5)));         List<List<Integer>> ans = obj.findSCC(V, edges);         System.out.println("Strongly Connected Components are:");         for (List<Integer> x : ans) {             for (int y : x) {                 System.out.print(y + " ");             }             System.out.println();         }     } }  // This code is contributed by shivamgupta310570 
Python
class GFG:     # dfs Function to reach destination     def dfs(self, curr, des, adj, vis):         # If current node is the destination, return True         if curr == des:             return True         vis[curr] = 1         for x in adj[curr]:             if not vis[x]:                 if self.dfs(x, des, adj, vis):                     return True         return False          # To tell whether there is a path from source to destination     def isPath(self, src, des, adj):         vis = [0] * (len(adj) + 1)         return self.dfs(src, des, adj, vis)          # Function to return all the strongly connected components of a graph.     def findSCC(self, n, a):         # Stores all the strongly connected components.         ans = []                  # Stores whether a vertex is a part of any Strongly Connected Component         is_scc = [0] * (n + 1)                  adj = [[] for _ in range(n + 1)]                  for i in range(len(a)):             adj[a[i][0]].append(a[i][1])                  # Traversing all the vertices         for i in range(1, n + 1):             if not is_scc[i]:                 # If a vertex i is not a part of any SCC, insert it into a new SCC list                 # and check for other vertices whether they can be part of this list.                 scc = [i]                 for j in range(i + 1, n + 1):                     # If there is a path from vertex i to vertex j and vice versa,                     # put vertex j into the current SCC list.                     if not is_scc[j] and self.isPath(i, j, adj) and self.isPath(j, i, adj):                         is_scc[j] = 1                         scc.append(j)                 # Insert the SCC containing vertex i into the final list.                 ans.append(scc)         return ans  # Driver Code Starts if __name__ == "__main__":     obj = GFG()     V = 5     edges = [         [1, 3], [1, 4], [2, 1], [3, 2], [4, 5]     ]     ans = obj.findSCC(V, edges)     print("Strongly Connected Components are:")     for x in ans:         for y in x:             print(y, end=" ")         print()          # This code is contributed by shivamgupta310570 
C#
using System; using System.Collections.Generic;  class GFG {     // dfs Function to reach destination     public bool Dfs(int curr, int des, List<List<int>> adj, List<int> vis)     {         // If curr node is the destination, return true         if (curr == des)         {             return true;         }         vis[curr] = 1;         foreach (var x in adj[curr])         {             if (vis[x] == 0)             {                 if (Dfs(x, des, adj, vis))                 {                     return true;                 }             }         }         return false;     }      // To tell whether there is a path from source to destination     public bool IsPath(int src, int des, List<List<int>> adj)     {         var vis = new List<int>(adj.Count + 1);         for (int i = 0; i < adj.Count + 1; i++)         {             vis.Add(0);         }         return Dfs(src, des, adj, vis);     }      // Function to return all the strongly connected components of a graph     public List<List<int>> FindSCC(int n, List<List<int>> a)     {         // Stores all the strongly connected components         var ans = new List<List<int>>();          // Stores whether a vertex is a part of any Strongly Connected Component         var isScc = new List<int>(n + 1);         for (int i = 0; i < n + 1; i++)         {             isScc.Add(0);         }          var adj = new List<List<int>>(n + 1);         for (int i = 0; i < n + 1; i++)         {             adj.Add(new List<int>());         }          for (int i = 0; i < a.Count; i++)         {             adj[a[i][0]].Add(a[i][1]);         }          // Traversing all the vertices         for (int i = 1; i <= n; i++)         {             if (isScc[i] == 0)             {                 // If a vertex i is not a part of any SCC                 // insert it into a new SCC list and check                 // for other vertices whether they can be                 // the part of this list.                 var scc = new List<int>();                 scc.Add(i);                  for (int j = i + 1; j <= n; j++)                 {                     // If there is a path from vertex i to                     // vertex j and vice versa, put vertex j                     // into the current SCC list.                     if (isScc[j] == 0 && IsPath(i, j, adj) && IsPath(j, i, adj))                     {                         isScc[j] = 1;                         scc.Add(j);                     }                 }                  // Insert the SCC containing vertex i into                 // the final list.                 ans.Add(scc);             }         }         return ans;     } }  // Driver Code Starts class Program {     static void Main(string[] args)     {         GFG obj = new GFG();         int V = 5;         List<List<int>> edges = new List<List<int>>         {             new List<int> { 1, 3 }, new List<int> { 1, 4 }, new List<int> { 2, 1 },             new List<int> { 3, 2 }, new List<int> { 4, 5 }         };         List<List<int>> ans = obj.FindSCC(V, edges);         Console.WriteLine("Strongly Connected Components are:");         foreach (var x in ans)         {             foreach (var y in x)             {                 Console.Write(y + " ");             }             Console.WriteLine();         }     } }   // This code is contributed by shivamgupta310570 
JavaScript
class GFG {     // Function to reach the destination using DFS     dfs(curr, des, adj, vis) {         // If the current node is the destination, return true         if (curr === des) {             return true;         }         vis[curr] = 1;         for (let x of adj[curr]) {             if (!vis[x]) {                 if (this.dfs(x, des, adj, vis)) {                     return true;                 }             }         }         return false;     }      // Check whether there is a path from source to destination     isPath(src, des, adj) {         const vis = new Array(adj.length + 1).fill(0);         return this.dfs(src, des, adj, vis);     }      // Function to find all strongly connected components of a graph     findSCC(n, a) {         // Stores all strongly connected components         const ans = [];          // Stores whether a vertex is part of any Strongly Connected Component         const is_scc = new Array(n + 1).fill(0);         const adj = new Array(n + 1).fill().map(() => []);          for (let i = 0; i < a.length; i++) {             adj[a[i][0]].push(a[i][1]);         }          // Traversing all the vertices         for (let i = 1; i <= n; i++) {             if (!is_scc[i]) {                 // If a vertex i is not part of any SCC,                 // insert it into a new SCC list and check                 // for other vertices that can be part of this list.                 const scc = [i];                 for (let j = i + 1; j <= n; j++) {                     // If there is a path from vertex i to                     // vertex j and vice versa, put vertex j                     // into the current SCC list.                     if (!is_scc[j] && this.isPath(i, j, adj) && this.isPath(j, i, adj)) {                         is_scc[j] = 1;                         scc.push(j);                     }                 }                 // Insert the SCC containing vertex i into the final list.                 ans.push(scc);             }         }         return ans;     } }  // Driver Code Starts const obj = new GFG(); const V = 5; const edges = [     [1, 3], [1, 4], [2, 1], [3, 2], [4, 5] ]; const ans = obj.findSCC(V, edges); console.log("Strongly Connected Components are:"); for (let x of ans) {     console.log(x.join(" ")); }  // This code is contributed by shivamgupta310570 

Output
Strongly Connected Components are: 1 2 3  4  5  

Time complexity: O((n^2) * (n + m)), because for each pair of vertices we are checking whether a path exists between them.
Auxiliary Space: O(N)

Efficient Approach for Finding Strongly Connected Components (SCCs)

To find SCCs in a graph, we can use algorithms like Kosaraju’s Algorithm or Tarjan’s Algorithm. Let’s explore these algorithms step-by-step.

1. Kosaraju’s Algorithm:

Kosaraju’s Algorithm involves two main phases:

  1. Performing Depth-First Search (DFS) on the Original Graph:
    • We first do a DFS on the original graph and record the finish times of nodes (i.e., the time at which the DFS finishes exploring a node completely).
  2. Performing DFS on the Transposed Graph:
    • We then reverse the direction of all edges in the graph to create the transposed graph.
    • Next, we perform a DFS on the transposed graph, considering nodes in decreasing order of their finish times recorded in the first phase.
    • Each DFS traversal in this phase will give us one SCC.

Here’s a simplified version of Kosaraju’s Algorithm:

  1. DFS on Original Graph: Record finish times.
  2. Transpose the Graph: Reverse all edges.
  3. DFS on Transposed Graph: Process nodes in order of decreasing finish times to find SCCs.

2. Tarjan’s Algorithm:

Tarjan’s Algorithm is more efficient because it finds SCCs in a single DFS pass using a stack and some additional bookkeeping:

  1. DFS Traversal: During the DFS, maintain an index for each node and the smallest index (low-link value) that can be reached from the node.
  2. Stack: Keep track of nodes currently in the recursion stack (part of the current SCC being explored).
  3. Identifying SCCs: When a node’s low-link value equals its index, it means we have found an SCC. Pop all nodes from the stack until we reach the current node.

Here’s a simplified outline of Tarjan’s Algorithm:

  1. Initialize index to 0.
  2. For each unvisited node, perform DFS.
    • Set the node’s index and low-link value.
    • Push the node onto the stack.
    • For each adjacent node, either perform DFS if it’s not visited or update the low-link value if it’s in the stack.
    • If the node’s low-link value equals its index, pop nodes from the stack to form an SCC.

Conclusion

Understanding and finding strongly connected components in a directed graph is essential for many applications in computer science. Kosaraju’s and Tarjan’s algorithms are efficient ways to identify SCCs, each with their own approach and advantages. By mastering these concepts, you can better analyze and optimize the structure and behavior of complex networks.



Next Article
Count all possible walks from a source to a destination with exactly k edges
author
kartik
Improve
Article Tags :
  • DSA
  • Graph
  • DFS
  • graph-connectivity
  • Visa
Practice Tags :
  • Visa
  • DFS
  • Graph

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