Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Detect cycle in an undirected graph
Next article icon

Detect Cycle in a Directed Graph

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

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]]

1
Cycle: 0 → 2 → 0

Output: true
Explanation: The diagram clearly shows a cycle 0 → 2 → 0

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

directed-1
No Cycle

Output: false
Explanation: The diagram clearly shows no cycle.

Table of Content

  • [Approach 1] Using DFS - O(V + E) Time and O(V) Space
  • [Approach 2] Using Topological Sorting - O(V + E) Time and O(V) Space

[Approach 1] Using DFS - O(V + E) Time and O(V) Space

The problem can be solved based on the following idea:

To find cycle in a directed graph we can use the Depth First Traversal (DFS) technique. It is based on the idea that there is a cycle in a graph only if there is a back edge [i.e., a node points to one of its ancestors in a DFS tree] present in the graph.

To detect a back edge, we need to keep track of the visited nodes that are in the current recursion stack [i.e., the current path that we are visiting]. Please note that all ancestors of a node are present in recursion call stack during DFS. So if there is an edge to an ancestor in DFS, then this is a back edge.

To keep track of vertices that are in recursion call stack, we use a boolean array where we use vertex number as an index. Whenever we begin recursive call for a vertex, we mark its entry as true and whenever the recursion call is about to end, we mark false.

Illustration:


Note: If the graph is disconnected then get the DFS forest and check for a cycle in individual graphs by checking back edges.

C++
#include <bits/stdc++.h> using namespace std;  // Utility function for DFS to detect a cycle in a directed graph bool isCyclicUtil(vector<vector<int>> &adj, int u, vector<bool> &visited, vector<bool> &recStack) {     // If the node is already in the recursion stack, a cycle is detected     if (recStack[u])         return true;      // If the node is already visited and not in recursion stack, no need to check again     if (visited[u])         return false;      // Mark the current node as visited and add it to the recursion stack     visited[u] = true;     recStack[u] = true;      // Recur for all neighbors     for (int x : adj[u])     {         if (isCyclicUtil(adj, x, visited, recStack))             return true;     }      // Remove the node from the recursion stack     recStack[u] = false;     return false; }  // Function to construct an adjacency list from edge list vector<vector<int>> constructadj(int V, vector<vector<int>> &edges) {     vector<vector<int>> adj(V);     for (auto &it : edges)     {         adj[it[0]].push_back(it[1]); // Directed edge from it[0] to it[1]     }     return adj; }  // Function to detect cycle in a directed graph bool isCyclic(int V, vector<vector<int>> &edges) {     // Construct the adjacency list     vector<vector<int>> adj = constructadj(V, edges);      // visited[] keeps track of visited nodes     // recStack[] keeps track of nodes in the current recursion stack     vector<bool> visited(V, false);     vector<bool> recStack(V, false);      // Check for cycles starting from every unvisited node     for (int i = 0; i < V; i++)     {         if (!visited[i] && isCyclicUtil(adj, i, visited, recStack))             return true; // Cycle found     }      return false; // No cycles detected }  int main() {     int V = 4; // Number of vertices      // Directed edges of the graph     vector<vector<int>> edges = {{0, 1}, {0, 2}, {1, 2}, {2, 0}, {2, 3}};      // Output whether the graph contains a cycle     cout << (isCyclic(V, edges) ? "true" : "false") << endl;      return 0; } 
Java
import java.util.*;  class GfG {      // Function to perform DFS and detect cycle in a     // directed graph     private static boolean isCyclicUtil(List<Integer>[] adj,                                         int u,                                         boolean[] visited,                                         boolean[] recStack)     {         // If the current node is already in the recursion         // stack, a cycle is detected         if (recStack[u])             return true;          // If already visited and not in recStack, it's not         // part of a cycle         if (visited[u])             return false;          // Mark the current node as visited and add it to         // the recursion stack         visited[u] = true;         recStack[u] = true;          // Recur for all adjacent vertices         for (int v : adj[u]) {             if (isCyclicUtil(adj, v, visited, recStack))                 return true;         }          // Backtrack: remove the vertex from recursion stack         recStack[u] = false;         return false;     }      // Function to construct adjacency list from edge list     private static List<Integer>[] constructAdj(         int V, int[][] edges)     {         // Create an array of lists         List<Integer>[] adj = new ArrayList[V];         for (int i = 0; i < V; i++) {             adj[i] = new ArrayList<>();         }          // Add edges to the adjacency list (directed)         for (int[] edge : edges) {             adj[edge[0]].add(edge[1]);         }          return adj;     }      // Main function to check if the directed graph contains     // a cycle     public static boolean isCyclic(int V, int[][] edges)     {         List<Integer>[] adj = constructAdj(V, edges);         boolean[] visited = new boolean[V];         boolean[] recStack = new boolean[V];          // Perform DFS from each unvisited vertex         for (int i = 0; i < V; i++) {             if (!visited[i]                 && isCyclicUtil(adj, i, visited, recStack))                 return true; // Cycle found         }          return false; // No cycle found     }      public static void main(String[] args)     {         int V = 4; // Number of vertices          // Directed edges of the graph         int[][] edges = {             { 0, 1 },             { 0, 2 },             { 1, 2 },             { 2,               0 }, // This edge creates a cycle (0 → 2 → 0)             { 2, 3 }         };          // Print result         System.out.println(isCyclic(V, edges) ? "true"                                               : "false");     } } 
Python
# Helper function for DFS-based cycle detection def isCyclicUtil(adj, u, visited, recStack):     # If the node is already in the current recursion stack, a cycle is detected     if recStack[u]:         return True      # If the node is already visited and not part of the recursion stack, skip it     if visited[u]:         return False      # Mark the current node as visited and add it to the recursion stack     visited[u] = True     recStack[u] = True      # Recur for all the adjacent vertices     for v in adj[u]:         if isCyclicUtil(adj, v, visited, recStack):             return True      # Remove the node from the recursion stack before returning     recStack[u] = False     return False  # Function to build adjacency list from edge list   def constructadj(V, edges):     adj = [[] for _ in range(V)]  # Create a list for each vertex     for u, v in edges:         adj[u].append(v)  # Add directed edge from u to v     return adj  # Main function to detect cycle in the directed graph   def isCyclic(V, edges):     adj = constructadj(V, edges)     visited = [False] * V       # To track visited vertices     recStack = [False] * V      # To track vertices in the current DFS path      # Try DFS from each vertex     for i in range(V):         if not visited[i] and isCyclicUtil(adj, i, visited, recStack):             return True  # Cycle found     return False  # No cycle found   # Example usage V = 4  # Number of vertices edges = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]]  # Output: True, because there is a cycle (0 → 2 → 0) print(isCyclic(V, edges)) 
C#
using System; using System.Collections.Generic;  class GfG {      // Function to check if the graph has a cycle using DFS     private static bool IsCyclicUtil(List<int>[] adj, int u,                                      bool[] visited,                                      bool[] recStack)     {         if (recStack[u])             return true;          if (visited[u])             return false;          visited[u] = true;         recStack[u] = true;          foreach(int v in adj[u])         {             if (IsCyclicUtil(adj, v, visited, recStack))                 return true;         }          recStack[u] = false;         return false;     }      // Function to construct adjacency list     private static List<int>[] Constructadj(int V,                                             int[][] edges)     {         List<int>[] adj = new List<int>[ V ];         for (int i = 0; i < V; i++) {             adj[i] = new List<int>();         }         foreach(var edge in edges)         {             adj[edge[0]].Add(edge[1]);         }         return adj;     }      // Function to check if a cycle exists in the graph     public static bool isCyclic(int V, int[][] edges)     {         List<int>[] adj = Constructadj(V, edges);         bool[] visited = new bool[V];         bool[] recStack = new bool[V];          for (int i = 0; i < V; i++) {             if (!visited[i]                 && IsCyclicUtil(adj, i, visited, recStack))                 return true;         }          return false;     }      public static void Main()     {         int V = 4;         int[][] edges             = { new int[] { 0, 1 }, new int[] { 0, 2 },                 new int[] { 1, 2 }, new int[] { 2, 0 },                 new int[] { 2, 3 } };          Console.WriteLine(isCyclic(V, edges));     } } 
JavaScript
// Helper function to perform DFS and detect cycle function isCyclicUtil(adj, u, visited, recStack) {     // If node is already in the recursion stack, cycle     // detected     if (recStack[u])         return true;      // If node is already visited and not in recStack, no     // need to check again     if (visited[u])         return false;      // Mark the node as visited and add it to the recursion     // stack     visited[u] = true;     recStack[u] = true;      // Recur for all neighbors of the current node     for (let v of adj[u]) {         if (isCyclicUtil(adj, v, visited, recStack))             return true; // If any path leads to a cycle,                          // return true     }      // Backtrack: remove the node from recursion stack     recStack[u] = false;     return false; // No cycle found in this path }  // Function to construct adjacency list from edge list function constructadj(V, edges) {     let adj = Array.from(         {length : V},         () => []); // Create an empty list for each vertex     for (let [u, v] of edges) {         adj[u].push(v); // Add directed edge from u to v     }     return adj; }  // Main function to detect cycle in directed graph function isCyclic(V, edges) {     let adj         = constructadj(V, edges); // Build adjacency list     let visited         = new Array(V).fill(false); // Track visited nodes     let recStack         = new Array(V).fill(false); // Track recursion stack      // Check each vertex (for disconnected components)     for (let i = 0; i < V; i++) {         if (!visited[i]             && isCyclicUtil(adj, i, visited, recStack))             return true; // Cycle found     }      return false; // No cycle detected }  // Example usage let V = 4; let edges =     [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ], [ 2, 0 ], [ 2, 3 ] ];  console.log(isCyclic(V, edges)); // Output: true 

Output
true 

Time Complexity: O(V + E), the Time Complexity of this method is the same as the time complexity of DFS traversal which is O(V+E).
Auxiliary Space: O(V), storing the visited array and recursion stack requires O(V) space.

We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.

In the below article, another O(V + E) method is discussed : Detect Cycle in a direct graph using colors

[Approach 2] Using Topological Sorting - O(V + E) Time and O(V) Space

Here we are using Kahn's algorithm for topological sorting, if it successfully removes all vertices from the graph, it's a DAG with no cycles. If there are remaining vertices with in-degrees greater than 0, it indicates the presence of at least one cycle in the graph. Hence, if we are not able to get all the vertices in topological sorting then there must be at least one cycle.

C++
#include <bits/stdc++.h> using namespace std;  // Function to construct adjacency list from the given edges vector<vector<int>> constructAdj(int V, vector<vector<int>> &edges) {     vector<vector<int>> adj(V);     for (auto &edge : edges)     {         adj[edge[0]].push_back(edge[1]);         // Directed edge from edge[0] to edge[1]     }     return adj; }  // Function to check if a cycle exists in the directed graph using Kahn's Algorithm (BFS) bool isCyclic(int V, vector<vector<int>> &edges) {     vector<vector<int>> adj = constructAdj(V, edges);     // Build the adjacency list      vector<int> inDegree(V, 0); // Array to store in-degree of each vertex     queue<int> q;               // Queue to store nodes with in-degree 0     int visited = 0;            // Count of visited (processed) nodes      // Step 1: Compute in-degrees of all vertices     for (int u = 0; u < V; ++u)     {         for (int v : adj[u])         {             inDegree[v]++;         }     }      //  Add all vertices with in-degree 0 to the queue     for (int u = 0; u < V; ++u)     {         if (inDegree[u] == 0)         {             q.push(u);         }     }      // Perform BFS (Topological Sort)     while (!q.empty())     {         int u = q.front();         q.pop();         visited++;          // Reduce in-degree of neighbors         for (int v : adj[u])         {             inDegree[v]--;             if (inDegree[v] == 0)             {                 // Add to queue when in-degree becomes 0                 q.push(v);             }         }     }      //  If visited nodes != total nodes, a cycle exists     return visited != V; }  int main() {     int V = 4; // Number of vertices     vector<vector<int>> edges = {{0, 1}, {0, 2}, {1, 2}, {2, 0}, {2, 3}};      // Output: true (cycle exists)     cout << (isCyclic(V, edges) ? "true" : "false") << endl;      return 0; } 
Java
import java.util.*;  class GfG {      // Function to construct an adjacency list from edge     // list     static List<Integer>[] constructadj(int V,                                         int[][] edges)     {         List<Integer>[] adj = new ArrayList[V];          // Initialize each adjacency list         for (int i = 0; i < V; i++) {             adj[i] = new ArrayList<>();         }          // Add directed edges to the adjacency list         for (int[] edge : edges) {             adj[edge[0]].add(edge[1]); // Directed edge from                                        // edge[0] to edge[1]         }          return adj;     }      // Function to check if the directed graph contains a     // cycle using Kahn's Algorithm     static boolean isCyclic(int V, int[][] edges)     {         List<Integer>[] adj             = constructadj(V, edges); //  Build graph          int[] inDegree             = new int[V]; // Array to store in-degree of                           // each vertex         Queue<Integer> q             = new LinkedList<>(); // Queue for BFS         int visited             = 0; // Count of visited (processed) nodes          //  Compute in-degrees of all vertices         for (int u = 0; u < V; u++) {             for (int v : adj[u]) {                 inDegree[v]++;             }         }          //  Enqueue all nodes with in-degree 0         for (int u = 0; u < V; u++) {             if (inDegree[u] == 0) {                 q.offer(u);             }         }          // Perform BFS (Topological Sort)         while (!q.isEmpty()) {             int u = q.poll();             visited++;              // Reduce in-degree of all adjacent vertices             for (int v : adj[u]) {                 inDegree[v]--;                 if (inDegree[v] == 0) {                     q.offer(v);                 }             }         }          //  If not all vertices were visited, there's a         //  cycle         return visited != V;     }      public static void main(String[] args)     {         int V = 4; // Number of vertices         int[][] edges = {             { 0, 1 }, { 0, 2 }, { 1, 2 }, { 2, 0 }, { 2, 3 }         };          // Output: true (cycle detected)         System.out.println(isCyclic(V, edges) ? "true"                                               : "false");     } } 
Python
from collections import deque  # Function to construct adjacency list from edge list   def constructadj(V, edges):     adj = [[] for _ in range(V)]  # Initialize empty list for each vertex     for u, v in edges:         adj[u].append(v)          # Directed edge from u to v     return adj  # Function to check for cycle using Kahn's Algorithm (BFS-based Topological Sort)   def isCyclic(V, edges):     adj = constructadj(V, edges)     in_degree = [0] * V     queue = deque()     visited = 0                       # Count of visited nodes      #  Calculate in-degree of each node     for u in range(V):         for v in adj[u]:             in_degree[v] += 1      #  Enqueue nodes with in-degree 0     for u in range(V):         if in_degree[u] == 0:             queue.append(u)      #  Perform BFS (Topological Sort)     while queue:         u = queue.popleft()         visited += 1          # Decrease in-degree of adjacent nodes         for v in adj[u]:             in_degree[v] -= 1             if in_degree[v] == 0:                 queue.append(v)      #  If visited != V, graph has a cycle     return visited != V   # Example usage V = 4 edges = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]]  # Output: true (because there is a cycle: 0 → 2 → 0) print("true" if isCyclic(V, edges) else "false") 
C#
using System; using System.Collections.Generic;  class GfG {      // Function to construct an adjacency list from the     // given edge list     static List<int>[] constructadj(int V, int[][] edges)     {         List<int>[] adj = new List<int>[ V ];          // Initialize each list in the array         for (int i = 0; i < V; i++) {             adj[i] = new List<int>();         }          // Populate adjacency list for directed graph         foreach(var edge in edges)         {             adj[edge[0]].Add(                 edge[1]); // Add directed edge from edge[0]                           // to edge[1]         }          return adj;     }      // Function to check whether the graph contains a cycle     // using Kahn's Algorithm     static bool isCyclic(int V, int[][] edges)     {         List<int>[] adj = constructadj(             V, edges); // Build adjacency list          int[] inDegree = new int[V];         Queue<int> q = new Queue<int>();         int visited = 0;          // Calculate in-degree of each vertex         for (int u = 0; u < V; u++) {             foreach(int v in adj[u]) { inDegree[v]++; }         }          // Add vertices with in-degree 0 to queue         for (int u = 0; u < V; u++) {             if (inDegree[u] == 0) {                 q.Enqueue(u);             }         }          // Process queue using BFS         while (q.Count > 0) {             int u = q.Dequeue();             visited++; // Count the visited node              // Decrease in-degree of adjacent vertices             foreach(int v in adj[u])             {                 inDegree[v]--;                 if (inDegree[v] == 0) {                     q.Enqueue(                         v); // Add vertex to queue when                             // in-degree becomes 0                 }             }         }          //  If not all vertices were visited, there's a         //  cycle         return visited != V;     }      // Main function to run the program     public static void Main()     {         int V = 4;          // Define edges of the graph (directed)         int[][] edges             = { new int[] { 0, 1 }, new int[] { 0, 2 },                 new int[] { 1, 2 }, new int[] { 2, 0 },                 new int[] { 2, 3 } };          // Output whether the graph contains a cycle         Console.WriteLine(isCyclic(V, edges) ? "true"                                              : "false");     } } 
JavaScript
// Function to construct the adjacency list from edge list function constructadj(V, edges) {     // Initialize an adjacency list with V empty arrays     let adj = Array.from({length : V}, () => []);      // Populate the adjacency list (directed edge u → v)     for (let [u, v] of edges) {         adj[u].push(v);     }      return adj; }  // Function to detect a cycle in a directed graph using // Kahn's Algorithm function isCyclic(V, edges) {     let adj = constructadj(V, edges);     let inDegree = new Array(V).fill(0);     let queue = [];     let visited = 0;      for (let u = 0; u < V; u++) {         for (let v of adj[u]) {             inDegree[v]++;         }     }     // Enqueue all nodes with in-degree 0     for (let u = 0; u < V; u++) {         if (inDegree[u] === 0) {             queue.push(u);         }     }      //  Process nodes with in-degree 0     while (queue.length > 0) {         let u = queue.shift(); // Dequeue         visited++; // Mark node as visited          // Reduce in-degree of adjacent nodes         for (let v of adj[u]) {             inDegree[v]--;             if (inDegree[v] === 0) {                 queue.push(                     v); // Enqueue if in-degree becomes 0             }         }     }      //  If not all nodes were visited, there's a cycle     return visited !== V; }  // Example usage const V = 4; const edges =     [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ], [ 2, 0 ], [ 2, 3 ] ];  // Output: true (cycle exists: 0 → 2 → 0) console.log(isCyclic(V, edges) ? "true" : "false"); 

Output
true 

Time Complexity: O(V + E), the time complexity of this method is the same as the time complexity of BFS traversal which is O(V+E).
Auxiliary Space: O(V), for creating queue and array indegree.

We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.



Next Article
Detect cycle in an undirected graph

K

kartik
Improve
Article Tags :
  • Graph
  • DSA
  • Microsoft
  • Amazon
  • Adobe
  • Oracle
  • Flipkart
  • Samsung
  • BankBazaar
  • MakeMyTrip
  • Rockstand
  • DFS
  • graph-cycle
Practice Tags :
  • Adobe
  • Amazon
  • BankBazaar
  • Flipkart
  • MakeMyTrip
  • Microsoft
  • Oracle
  • Rockstand
  • Samsung
  • DFS
  • Graph

Similar Reads

    Graph Algorithms
    Graph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
    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. Difference Between Graph and Tree What is Graph?A grap
    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 pick
    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: GraphTr
    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.Difference between BFS and DFSParametersBFSDFSStands forBFS stands fo
    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]]Cycle: 0 → 2 → 0 Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 0 Input: V = 4, edges[][] =
    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]]Undirected Graph with 4 vertices and 4 edgesOutput: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0Input: V = 4, edges[][] = [[0,
    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 true
    9 min read
    Detect a negative cycle in a Graph | (Bellman Ford)
    Given a directed weighted graph, your task is to find whether the given graph contains any negative cycles that are reachable from the source vertex (e.g., node 0).Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value.Example:Input: V = 4, edges[][] = [[0, 3, 6], [1
    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