Java Program to Check 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.

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
 
public class CheckCycle
{
    private Stack<Integer> stack;
    private int adjacencyMatrix[][];
 
    public CheckCycle() 
    {
        stack = new Stack<Integer>();
    }
 
    public void dfs(int adjacency_matrix[][], int source)
    {
        int number_of_nodes = adjacency_matrix.length - 1;
 
        adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
        for (int sourcevertex = 1; sourcevertex <= number_of_nodes; sourcevertex++)
        {
            for (int destinationvertex = 1; destinationvertex <= number_of_nodes; destinationvertex++)
            {
                adjacencyMatrix[sourcevertex][destinationvertex] =
                   adjacency_matrix[sourcevertex][destinationvertex];
            }
        }
 
        int visited[] = new int[number_of_nodes + 1];		
        int element = source;		
        int destination = source;			
        visited = 1;		
        stack.push(source);
 
        while (!stack.isEmpty())
        {
            element = stack.peek();
            destination = element;	
	    while (destination <= number_of_nodes)
	    {
                if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 1)
                {
                    if (stack.contains(destination))
                    {	
                        System.out.println("The Graph contains cycle");
                        return;	
                    }
                }
 
              	if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 0)
	        {
                    stack.push(destination);
                    visited[destination] = 1;
                    adjacencyMatrix[element][destination] = 0;
                    element = destination;
                    destination = 1;
	            continue;
                }
                destination++;
	    }
            stack.pop();	
        }	
    }
 
    public static void main(String...arg)
    {
        int number_of_nodes, source;
        Scanner scanner = null;
 	try
        {
	    System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_of_nodes = scanner.nextInt();
 
	    int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
	    System.out.println("Enter the adjacency matrix");
	    for (int i = 1; i <= number_of_nodes; i++)
	        for (int j = 1; j <= number_of_nodes; j++)
                    adjacency_matrix[i][j] = scanner.nextInt();
 
            System.out.println("Enter the source for the graph");
            source = scanner.nextInt(); 
 
            CheckCycle checkCycle = new CheckCycle();
            checkCycle.dfs(adjacency_matrix, source);
 
        }catch(InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input format");
        } 	
        scanner.close();	
    }	
}
$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

Related posts:

Java Program to implement Bit Matrix
ETL with Spring Cloud Data Flow
Tạo chương trình Java đầu tiên sử dụng Eclipse
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Java Program to Compare Binary and Sequential Search
Convert XML to JSON Using Jackson
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Java – InputStream to Reader
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Lớp Properties trong java
Send email with authentication
Introduction to Spring Cloud OpenFeign
Java Program to Delete a Particular Node in a Tree Without Using Recursion
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Java Program to Implement LinkedBlockingDeque API
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Java Program to Compute Cross Product of Two Vectors
Java Program to Implement Shell Sort
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Java Program to Find Number of Articulation points in a Graph
Java Program to Perform Searching Using Self-Organizing Lists
Một số nguyên tắc, định luật trong lập trình
“Stream has already been operated upon or closed” Exception in Java
Overview of the java.util.concurrent
Mapping a Dynamic JSON Object with Jackson
Guide to the ConcurrentSkipListMap
Bootstrapping Hibernate 5 with Spring
Java Program to Find a Good Feedback Vertex Set
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Guide to Spring 5 WebFlux
Logging in Spring Boot
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers