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
  • Tutorial on Randomized Algorithms
  • Importance of Randomized Algorithms
  • Random Variables
  • Randomized Binary Search Algorithm
  • Randomized Quick Sort Algorithm
  • Las Vegas & Monte Carlo Algorithms
  • Birthday Paradox
  • Treap
  • Skip List
  • Generate Captcha
  • Fisher-Yates Shuffle
  • Reservoir Sampling
  • Freivald's Algorithm
  • 1/2 Approximate Median
Open In App
Next Article:
Dinic's algorithm for Maximum Flow
Next article icon

Introduction and implementation of Karger’s algorithm for Minimum Cut

Last Updated : 19 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an undirected and unweighted graph, find the smallest cut (smallest number of edges that disconnects the graph into two components). 
The input graph may have parallel edges.

For example consider the following example, the smallest cut has 2 edges.

Kargerfirst

A Simple Solution use Max-Flow based s-t cut algorithm to find minimum cut. Consider every pair of vertices as source ‘s’ and sink ‘t’, and call minimum s-t cut algorithm to find the s-t cut. Return minimum of all s-t cuts. Best possible time complexity of this algorithm is O(V5) for a graph. [How? there are total possible V2 pairs and s-t cut algorithm for one pair takes O(V*E) time and E = O(V2)]. 

Below is simple Karger’s Algorithm for this purpose. Below Karger’s algorithm can be implemented in O(E) = O(V2) time. 

1)  Initialize contracted graph CG as copy of original graph
2) While there are more than 2 vertices.
a) Pick a random edge (u, v) in the contracted graph.
b) Merge (or contract) u and v into a single vertex (update
the contracted graph).
c) Remove self-loops
3) Return cut represented by two vertices.

Let us understand above algorithm through the example given.
Let the first randomly picked vertex be ‘a‘ which connects vertices 0 and 1. We remove this edge and contract the graph (combine vertices 0 and 1). We get the following graph. 

Karger2

Let the next randomly picked edge be ‘d’. We remove this edge and combine vertices (0,1) and 3. 

Karger3

We need to remove self-loops in the graph. So we remove edge ‘c’ 

Karger4

Now graph has two vertices, so we stop. The number of edges in the resultant graph is the cut produced by Karger’s algorithm.
Karger’s algorithm is a Monte Carlo algorithm and cut produced by it may not be minimum. For example, the following diagram shows that a different order of picking random edges produces a min-cut of size 3.

Karger1


Below is the implementation of above algorithm. The input graph is represented as a collection of edges and union-find data structure is used to keep track of components. 
 

C++
// Karger's algorithm to find Minimum Cut in an // undirected, unweighted and connected graph. #include <iostream> //#include <stdlib.h> #include <time.h>  // a structure to represent a unweighted edge in graph struct Edge {     int src, dest; };  // a structure to represent a connected, undirected // and unweighted graph as a collection of edges. struct Graph {     // V-> Number of vertices, E-> Number of edges     int V, E;      // graph is represented as an array of edges.     // Since the graph is undirected, the edge     // from src to dest is also edge from dest     // to src. Both are counted as 1 edge here.     Edge* edge; };  // A structure to represent a subset for union-find struct subset {     int parent;     int rank; };  // Function prototypes for union-find (These functions are defined // after kargerMinCut() ) int find(struct subset subsets[], int i); void Union(struct subset subsets[], int x, int y);  // A very basic implementation of Karger's randomized // algorithm for finding the minimum cut. Please note // that Karger's algorithm is a Monte Carlo Randomized algo // and the cut returned by the algorithm may not be // minimum always int kargerMinCut(struct Graph* graph) {     // Get data of given graph     int V = graph->V, E = graph->E;     Edge *edge = graph->edge;      // Allocate memory for creating V subsets.     struct subset *subsets = new subset[V];      // Create V subsets with single elements     for (int v = 0; v < V; ++v)     {         subsets[v].parent = v;         subsets[v].rank = 0;     }      // Initially there are V vertices in     // contracted graph     int vertices = V;      // Keep contracting vertices until there are     // 2 vertices.     while (vertices > 2)     {        // Pick a random edge        int i = rand() % E;         // Find vertices (or sets) of two corners        // of current edge        int subset1 = find(subsets, edge[i].src);        int subset2 = find(subsets, edge[i].dest);         // If two corners belong to same subset,        // then no point considering this edge        if (subset1 == subset2)          continue;         // Else contract the edge (or combine the        // corners of edge into one vertex)        else        {           printf("Contracting edge %d-%d\n",                  edge[i].src, edge[i].dest);           vertices--;           Union(subsets, subset1, subset2);        }     }      // Now we have two vertices (or subsets) left in     // the contracted graph, so count the edges between     // two components and return the count.     int cutedges = 0;     for (int i=0; i<E; i++)     {         int subset1 = find(subsets, edge[i].src);         int subset2 = find(subsets, edge[i].dest);         if (subset1 != subset2)           cutedges++;     }      return cutedges; }  // A utility function to find set of an element i // (uses path compression technique) int find(struct subset subsets[], int i) {     // find root and make root as parent of i     // (path compression)     if (subsets[i].parent != i)       subsets[i].parent =              find(subsets, subsets[i].parent);      return subsets[i].parent; }  // A function that does union of two sets of x and y // (uses union by rank) void Union(struct subset subsets[], int x, int y) {     int xroot = find(subsets, x);     int yroot = find(subsets, y);      // Attach smaller rank tree under root of high     // rank tree (Union by Rank)     if (subsets[xroot].rank < subsets[yroot].rank)         subsets[xroot].parent = yroot;     else if (subsets[xroot].rank > subsets[yroot].rank)         subsets[yroot].parent = xroot;      // If ranks are same, then make one as root and     // increment its rank by one     else     {         subsets[yroot].parent = xroot;         subsets[xroot].rank++;     } }  // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) {     Graph* graph = new Graph;     graph->V = V;     graph->E = E;     graph->edge = new Edge[E];     return graph; }  // Driver program to test above functions int main() {     /* Let us create following unweighted graph         0------1         | \    |         |   \  |         |     \|         2------3   */     int V = 4;  // Number of vertices in graph     int E = 5;  // Number of edges in graph     struct Graph* graph = createGraph(V, E);      // add edge 0-1     graph->edge[0].src = 0;     graph->edge[0].dest = 1;      // add edge 0-2     graph->edge[1].src = 0;     graph->edge[1].dest = 2;      // add edge 0-3     graph->edge[2].src = 0;     graph->edge[2].dest = 3;      // add edge 1-3     graph->edge[3].src = 1;     graph->edge[3].dest = 3;      // add edge 2-3     graph->edge[4].src = 2;     graph->edge[4].dest = 3;      // Use a different seed value for every run.     srand(time(NULL));      printf("\nCut found by Karger's randomized algo is %d\n",            kargerMinCut(graph));      return 0; } 
Java
// Java program to implement the Karger's algorithm to find // Minimum Cut in an // undirected, unweighted and connected graph.  import java.io.*; import java.util.*;  class GFG {      // a structure to represent a unweighted edge in graph     public static class Edge {         int src, dest;         Edge(int s, int d)         {             this.src = s;             this.dest = d;         }     }      // a structure to represent a connected, undirected     // and unweighted graph as a collection of edges.     public static class Graph {         // V-> Number of vertices, E-> Number of edges         int V, E;          // graph is represented as an array of edges.         // Since the graph is undirected, the edge         // from src to dest is also edge from dest         // to src. Both are counted as 1 edge here.         Edge edge[];         Graph(int v, int e)         {             this.V = v;             this.E = e;             this.edge = new Edge[e];             /*for(int i=0;i<e;i++){                 this.edge[i]=new Edge(-1,-1);             }*/         }     }      // A structure to represent a subset for union-find     public static class subset {         int parent;         int rank;         subset(int p, int r)         {             this.parent = p;             this.rank = r;         }     }      // A very basic implementation of Karger's randomized     // algorithm for finding the minimum cut. Please note     // that Karger's algorithm is a Monte Carlo Randomized     // algo and the cut returned by the algorithm may not be     // minimum always     public static int kargerMinCut(Graph graph)     {         // Get data of given graph         int V = graph.V, E = graph.E;         Edge edge[] = graph.edge;          // Allocate memory for creating V subsets.         subset subsets[] = new subset[V];          // Create V subsets with single elements         for (int v = 0; v < V; ++v) {             subsets[v] = new subset(v, 0);         }          // Initially there are V vertices in         // contracted graph         int vertices = V;          // Keep contracting vertices until there are         // 2 vertices.         while (vertices > 2) {             // Pick a random edge             int i = ((int)(Math.random() * 10)) % E;              // Find vertices (or sets) of two corners             // of current edge             int subset1 = find(subsets, edge[i].src);             int subset2 = find(subsets, edge[i].dest);              // If two corners belong to same subset,             // then no point considering this edge             if (subset1 == subset2) {                 continue;             }              // Else contract the edge (or combine the             // corners of edge into one vertex)             else {                 System.out.println("Contracting edge "                                    + edge[i].src + "-"                                    + edge[i].dest);                 vertices--;                 Union(subsets, subset1, subset2);             }         }          // Now we have two vertices (or subsets) left in         // the contracted graph, so count the edges between         // two components and return the count.         int cutedges = 0;         for (int i = 0; i < E; i++) {             int subset1 = find(subsets, edge[i].src);             int subset2 = find(subsets, edge[i].dest);             if (subset1 != subset2) {                 cutedges++;             }         }          return cutedges;     }      // A utility function to find set of an element i     // (uses path compression technique)     public static int find(subset subsets[], int i)     {         // find root and make root as parent of i         // (path compression)         if (subsets[i].parent != i) {             subsets[i].parent                 = find(subsets, subsets[i].parent);         }         return subsets[i].parent;     }      // A function that does union of two sets of x and y     // (uses union by rank)     public static void Union(subset subsets[], int x, int y)     {         int xroot = find(subsets, x);         int yroot = find(subsets, y);          // Attach smaller rank tree under root of high         // rank tree (Union by Rank)         if (subsets[xroot].rank < subsets[yroot].rank) {             subsets[xroot].parent = yroot;         }         else {             if (subsets[xroot].rank > subsets[yroot].rank) {                 subsets[yroot].parent = xroot;             }             // If ranks are same, then make one as root and             // increment its rank by one             else {                 subsets[yroot].parent = xroot;                 subsets[xroot].rank++;             }         }     }      // Driver program to test above functions     public static void main(String[] args)     {         /* Let us create following unweighted graph             0------1             | \    |             |   \  |             |     \|             2------3   */         int V = 4; // Number of vertices in graph         int E = 5; // Number of edges in graph          // Creates a graph with V vertices and E edges         Graph graph = new Graph(V, E);          // add edge 0-1         graph.edge[0] = new Edge(0, 1);          // add edge 0-2         graph.edge[1] = new Edge(0, 2);          // add edge 0-3         graph.edge[2] = new Edge(0, 3);          // add edge 1-3         graph.edge[3] = new Edge(1, 3);          // add edge 2-3         graph.edge[4] = new Edge(2, 3);          System.out.println(             "Cut found by Karger's randomized algo is "             + kargerMinCut(graph));     } } // This code is contributed by shruti456rawal 
Python3
# Karger's algorithm to find Minimum Cut in an # undirected, unweighted and connected graph. import random  # a class to represent a unweighted edge in graph class Edge:     def __init__(self, s, d):         self.src = s         self.dest = d  # a class to represent a connected, undirected # and unweighted graph as a collection of edges. class Graph:      # V-> Number of vertices, E-> Number of edges     def __init__(self, v, e):         self.V = v         self.E = e          # graph is represented as an array of edges.         # Since the graph is undirected, the edge         # from src to dest is also edge from dest         # to src. Both are counted as 1 edge here.         self.edge = []  # A class to represent a subset for union-find class subset:     def __init__(self, p, r):         self.parent = p         self.rank = r  # A very basic implementation of Karger's randomized # algorithm for finding the minimum cut. Please note # that Karger's algorithm is a Monte Carlo Randomized algo # and the cut returned by the algorithm may not be # minimum always def kargerMinCut(graph):      # Get data of given graph     V = graph.V     E = graph.E     edge = graph.edge      # Allocate memory for creating V subsets.     subsets = []      # Create V subsets with single elements     for v in range(V):         subsets.append(subset(v, 0))      # Initially there are V vertices in     # contracted graph     vertices = V      # Keep contracting vertices until there are     # 2 vertices.     while vertices > 2:          # Pick a random edge         i = int(10 * random.random()) % E          # Find vertices (or sets) of two corners         # of current edge         subset1 = find(subsets, edge[i].src)         subset2 = find(subsets, edge[i].dest)          # If two corners belong to same subset,         # then no point considering this edge         if subset1 == subset2:             continue          # Else contract the edge (or combine the         # corners of edge into one vertex)         else:             print("Contracting edge " +                   str(edge[i].src) + "-" + str(edge[i].dest))             vertices -= 1             Union(subsets, subset1, subset2)      # Now we have two vertices (or subsets) left in     # the contracted graph, so count the edges between     # two components and return the count.     cutedges = 0     for i in range(E):         subset1 = find(subsets, edge[i].src)         subset2 = find(subsets, edge[i].dest)         if subset1 != subset2:             cutedges += 1      return cutedges  # A utility function to find set of an element i # (uses path compression technique)   def find(subsets, i):      # find root and make root as parent of i     # (path compression)     if subsets[i].parent != i:         subsets[i].parent = find(subsets, subsets[i].parent)      return subsets[i].parent  # A function that does union of two sets of x and y # (uses union by rank) def Union(subsets, x, y):     xroot = find(subsets, x)     yroot = find(subsets, y)      # Attach smaller rank tree under root of high     # rank tree (Union by Rank)     if subsets[xroot].rank < subsets[yroot].rank:         subsets[xroot].parent = yroot     elif subsets[xroot].rank > subsets[yroot].rank:         subsets[yroot].parent = xroot      # If ranks are same, then make one as root and     # increment its rank by one     else:         subsets[yroot].parent = xroot         subsets[xroot].rank += 1  # Driver program to test above functions def main():      # Let us create following unweighted graph     # 0------1     # | \    |     # |  \   |     # |   \  |     # |    \ |     # 3------2     V = 4     E = 5     graph = Graph(V, E)      # add edge 0-1     graph.edge.append(Edge(0, 1))      # add edge 0-2     graph.edge.append(Edge(0, 2))      # add edge 0-3     graph.edge.append(Edge(0, 3))      # add edge 1-2     graph.edge.append(Edge(1, 2))      # add edge 2-3     graph.edge.append(Edge(2, 3))      r = random.random()     res = kargerMinCut(graph)     print("Cut found by Karger's randomized algo is", res)   if __name__ == '__main__':     main() 
C#
using System; using System.IO; using System.Collections.Generic;  class GFG {     // a structure to represent a unweighted edge in graph     public class Edge {         public int src, dest;         public Edge(int s, int d)         {             this.src = s;             this.dest = d;         }     }      // a structure to represent a connected, undirected     // and unweighted graph as a collection of edges.     public class Graph {         // V-> Number of vertices, E-> Number of edges         public int V, E;          // graph is represented as an array of edges.         // Since the graph is undirected, the edge         // from src to dest is also edge from dest         // to src. Both are counted as 1 edge here.         public Edge[] edge;         public Graph(int v, int e)         {             this.V = v;             this.E = e;             this.edge = new Edge[e];         }     }      // A structure to represent a subset for union-find     public class subset {         public int parent;         public int rank;         public subset(int p, int r)         {             this.parent = p;             this.rank = r;         }     }      // A very basic implementation of Karger's randomized     // algorithm for finding the minimum cut. Please note     // that Karger's algorithm is a Monte Carlo Randomized     // algo and the cut returned by the algorithm may not be     // minimum always     public static int kargerMinCut(Graph graph)     {         // Get data of given graph         int V = graph.V, E = graph.E;         Edge[] edge = graph.edge;          // Allocate memory for creating V subsets.         subset[] subsets = new subset[V];          // Create V subsets with single elements         for (int v = 0; v < V; ++v) {             subsets[v] = new subset(v, 0);         }          // Initially there are V vertices in         // contracted graph         int vertices = V;          // Keep contracting vertices until there are         // 2 vertices.         while (vertices > 2) {             // Pick a random edge             int i = ((int)(new Random().NextDouble() * 10))                     % E;              // Find vertices (or sets) of two corners             // of current edge             int subset1 = find(subsets, edge[i].src);             int subset2 = find(subsets, edge[i].dest);              // If two corners belong to same subset,             // then no point considering this edge             if (subset1 == subset2) {                 continue;             }              // Else contract the edge (or combine the             // corners of edge into one vertex)             else {                 Console.WriteLine("Contracting edge "                                   + edge[i].src + "-"                                   + edge[i].dest);                 vertices--;                 Union(subsets, subset1, subset2);             }         }          // Now we have two vertices (or subsets) left in         // the contracted graph, so count the edges between         // two components and return the count.         int cutedges = 0;         for (int i = 0; i < E; i++) {             int subset1 = find(subsets, edge[i].src);             int subset2 = find(subsets, edge[i].dest);             if (subset1 != subset2) {                 cutedges++;             }         }         return cutedges;     }      // A utility function to find set of an element i     // (uses path compression technique)     public static int find(subset[] subsets, int i)     {         // find root and make root as parent of i         // (path compression)         if (subsets[i].parent != i) {             subsets[i].parent                 = find(subsets, subsets[i].parent);         }          return subsets[i].parent;     }      // A function that does union of two sets of x and y     // (uses union by rank)     public static void Union(subset[] subsets, int x, int y)     {         int xroot = find(subsets, x);         int yroot = find(subsets, y);          // Attach smaller rank tree under root of high         // rank tree (Union by Rank)         if (subsets[xroot].rank < subsets[yroot].rank) {             subsets[xroot].parent = yroot;         }         else if (subsets[xroot].rank                  > subsets[yroot].rank) {             subsets[yroot].parent = xroot;         }          // If ranks are same, then make one as root and         // increment its rank by one         else {             subsets[yroot].parent = xroot;             subsets[xroot].rank++;         }     }      // Driver program to test above functions     public static void Main()     {         // Let us create following unweighted graph         // 0------1         // | \    |         // |  \   |         // |   \  |         // |    \ |         // 3------2         int V = 4, E = 5;         Graph graph = new Graph(V, E);          // add edge 0-1         graph.edge[0] = new Edge(0, 1);          // add edge 0-2         graph.edge[1] = new Edge(0, 2);          // add edge 0-3         graph.edge[2] = new Edge(0, 3);          // add edge 1-2         graph.edge[3] = new Edge(1, 2);          // add edge 2-3         graph.edge[4] = new Edge(2, 3);          // Use a different seed value for every run.         Random r = new Random();         int res = kargerMinCut(graph);         Console.WriteLine(             "Cut found by Karger's randomized algo is "             + res);     } } // this code is contributed by devendrasalunke 
JavaScript
class Edge {     constructor(s, d) {         this.src = s;         this.dest = d;     } }  class Graph {     constructor(v, e) {         this.V = v;         this.E = e;         this.edge = [];     } }  class subset {     constructor(p, r) {         this.parent = p;         this.rank = r;     } }  function kargerMinCut(graph) {     let V = graph.V;     let E = graph.E;     let edge = graph.edge;      let subsets = [];      for (let v = 0; v < V; v++) {         subsets[v] = new subset(v, 0);     }      let vertices = V;      while (vertices > 2) {         let i = Math.floor(Math.random() * 10) % E;          let subset1 = find(subsets, edge[i].src);         let subset2 = find(subsets, edge[i].dest);          if (subset1 === subset2) {             continue;         } else {             console.log("Contracting edge " + edge[i].src + "-"                           + edge[i].dest);             vertices--;             Union(subsets, subset1, subset2);         }     }      let cutedges = 0;     for (let i = 0; i < E; i++) {         let subset1 = find(subsets, edge[i].src);         let subset2 = find(subsets, edge[i].dest);         if (subset1 !== subset2) {             cutedges++;         }     }     return cutedges; }  function find(subsets, i) {     if (subsets[i].parent !== i) {         subsets[i].parent = find(subsets, subsets[i].parent);     }     return subsets[i].parent; }  function Union(subsets, x, y) {     let xroot = find(subsets, x);     let yroot = find(subsets, y);      if (subsets[xroot].rank < subsets[yroot].rank) {         subsets[xroot].parent = yroot;     } else if (subsets[xroot].rank > subsets[yroot].rank) {         subsets[yroot].parent = xroot;     } else {         subsets[yroot].parent = xroot;         subsets[xroot].rank++;     } } // Driver program to test above functions function main() {   // Let us create following unweighted graph   // 0------1   // | \    |   // |  \   |   // |   \  |   // |    \ |   // 3------2   let V = 4, E = 5;   let graph = new Graph(V, E);    // add edge 0-1   graph.edge[0] = new Edge(0, 1);    // add edge 0-2   graph.edge[1] = new Edge(0, 2);    // add edge 0-3   graph.edge[2] = new Edge(0, 3);    // add edge 1-2   graph.edge[3] = new Edge(1, 2);    // add edge 2-3   graph.edge[4] = new Edge(2, 3);    // Use a different seed value for every run.   let r = Math.random();   let res = kargerMinCut(graph);   console.log(     "Cut found by Karger's randomized algo is " + res   ); }  main(); // this code is contributed by writer  

Output
Contracting edge 0-1 Contracting edge 1-3  Cut found by Karger's randomized algo is 2

Note that the above program is based on outcome of a random function and may produce different output.
In this post, we have discussed simple Karger’s algorithm and have seen that the algorithm doesn’t always produce min-cut. The above algorithm produces min-cut with probability greater or equal to that 1/(n2). See next post on Analysis and Applications of Karger’s Algorithm, applications, proof of this probability and improvements are discussed. 

Complexity Analysis : 

Time Complexity : O(EV^2), where E is the number of edges and V is the number of vertices in the graph. The algorithm is not guaranteed to always find the minimum cut, but it has a high probability of doing so with a large number of iterations. The time complexity is dominated by the while loop, which runs for V-2 iterations and performs a constant amount of work on each iteration. The work on each iteration includes finding the subset of an element, union of subsets, and contract the edge. So, the time complexity is O(EV^2) where V is number of vertices and E is number of edges.

Auxiliary Space : The Auxiliary Space of the above code is O(E + V), where E is the number of edges in the graph and V is the number of vertices. This is because the program uses an adjacency list to store the graph, which requires O(E) space. It also uses two lists to store visited vertices and the BFS queue, which require O(V) space. In total, the program uses O(E + V) space.



Next Article
Dinic's algorithm for Maximum Flow
author
kartik
Improve
Article Tags :
  • DSA
  • Graph
  • Randomized
  • graph-connectivity
Practice Tags :
  • 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