Java Program to Detect Cycle in a Graph using Graph Traversal

«
»
This Java program,performs the DFS traversal on the given graph represented by a adjacency matrix to check for cycles in the graph.the DFS traversal makes use of an stack.

Here is the source code of the Java program to check for cycle in graph.The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. import java.util.InputMismatchException;
  2. import java.util.Scanner;
  3. import java.util.Stack;
  4.  
  5. public class CheckCycle
  6. {
  7.     private Stack<Integer> stack;
  8.     private int adjacencyMatrix[][];
  9.  
  10.     public CheckCycle() 
  11.     {
  12.         stack = new Stack<Integer>();
  13.     }
  14.  
  15.     public void dfs(int adjacency_matrix[][], int source)
  16.     {
  17.         int number_of_nodes = adjacency_matrix[source].length - 1;
  18.  
  19.         adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
  20.         for (int sourcevertex = 1; sourcevertex <= number_of_nodes; sourcevertex++)
  21.         {
  22.             for (int destinationvertex = 1; destinationvertex <= number_of_nodes; destinationvertex++)
  23.             {
  24.                 adjacencyMatrix[sourcevertex][destinationvertex] =
  25.                    adjacency_matrix[sourcevertex][destinationvertex];
  26.             }
  27.         }
  28.  
  29.         int visited[] = new int[number_of_nodes + 1];		
  30.         int element = source;		
  31.         int destination = source;			
  32.         visited[source] = 1;		
  33.         stack.push(source);
  34.  
  35.         while (!stack.isEmpty())
  36.         {
  37.             element = stack.peek();
  38.             destination = element;	
  39. 	    while (destination <= number_of_nodes)
  40. 	    {
  41.                 if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 1)
  42.                 {
  43.                     if (stack.contains(destination))
  44.                     {	
  45.                         System.out.println("The Graph contains cycle");
  46.                         return;	
  47.                     }
  48.                 }
  49.  
  50.               	if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 0)
  51. 	        {
  52.                     stack.push(destination);
  53.                     visited[destination] = 1;
  54.                     adjacencyMatrix[element][destination] = 0;
  55.                     element = destination;
  56.                     destination = 1;
  57. 	            continue;
  58.                 }
  59.                 destination++;
  60. 	    }
  61.             stack.pop();	
  62.         }	
  63.     }
  64.  
  65.     public static void main(String...arg)
  66.     {
  67.         int number_of_nodes, source;
  68.         Scanner scanner = null;
  69.  	try
  70.         {
  71. 	    System.out.println("Enter the number of nodes in the graph");
  72.             scanner = new Scanner(System.in);
  73.             number_of_nodes = scanner.nextInt();
  74.  
  75. 	    int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
  76. 	    System.out.println("Enter the adjacency matrix");
  77. 	    for (int i = 1; i <= number_of_nodes; i++)
  78. 	        for (int j = 1; j <= number_of_nodes; j++)
  79.                     adjacency_matrix[i][j] = scanner.nextInt();
  80.  
  81.             System.out.println("Enter the source for the graph");
  82.             source = scanner.nextInt(); 
  83.  
  84.             CheckCycle checkCycle = new CheckCycle();
  85.             checkCycle.dfs(adjacency_matrix, source);
  86.  
  87.         }catch(InputMismatchException inputMismatch)
  88.         {
  89.             System.out.println("Wrong Input format");
  90.         } 	
  91.         scanner.close();	
  92.     }	
  93. }

$javac CheckCycle.java
$java CheckCycle
Enter the number of nodes in the graph
5
Enter the adjacency matrix
0 0 0 1 0
1 0 1 0 0
0 0 0 0 0
0 1 0 0 1 
0 0 1 0 0 
Enter the source for the graph
1
The Graph contains a cycle

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.