Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph

This is a java program to find topological sort of DAG. In computer science, a topological sort (sometimes abbreviated topsort or toposort) or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time.

Here is the source code of the Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

package com.sanfoundry.graph;
 
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
 
public class DigraphTopologicalSortingDFS
{
    private Stack<Integer> stack;
 
    public DigraphTopologicalSortingDFS()
    {
        stack = new Stack<Integer>();
    }
 
    public int[] topological(int adjacency_matrix[][], int source)
            throws NullPointerException
    {
        int number_of_nodes = adjacency_matrix.length - 1;
        int[] topological_sort = new int[number_of_nodes + 1];
        int pos = 1;
        int j;
        int visited[] = new int[number_of_nodes + 1];
        int element = source;
        int i = source;
        visited = 1;
        stack.push(source);
        while (!stack.isEmpty())
        {
            element = stack.peek();
            while (i <= number_of_nodes)
            {
                if (adjacency_matrix[element][i] == 1 && visited[i] == 1)
                {
                    if (stack.contains(i))
                    {
                        System.out.println("TOPOLOGICAL SORT NOT POSSIBLE");
                        return null;
                    }
                }
                if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
                {
                    stack.push(i);
                    visited[i] = 1;
                    element = i;
                    i = 1;
                    continue;
                }
                i++;
            }
            j = stack.pop();
            topological_sort[pos++] = j;
            i = ++j;
        }
        return topological_sort;
    }
 
    public static void main(String... arg)
    {
        int number_no_nodes, source;
        Scanner scanner = null;
        int topological_sort[] = null;
        try
        {
            System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_no_nodes = scanner.nextInt();
            int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1];
            System.out.println("Enter the adjacency matrix");
            for (int i = 1; i <= number_no_nodes; i++)
                for (int j = 1; j <= number_no_nodes; j++)
                    adjacency_matrix[i][j] = scanner.nextInt();
            System.out.println("Enter the source for the graph");
            source = scanner.nextInt();
            System.out
                    .println("The Topological sort for the graph is given by ");
            DigraphTopologicalSortingDFS toposort = new DigraphTopologicalSortingDFS();
            topological_sort = toposort.topological(adjacency_matrix, source);
            for (int i = topological_sort.length - 1; i > 0; i--)
            {
                if (topological_sort[i] != 0)
                    System.out.print(topological_sort[i] + "\t");
            }
        }
        catch (InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input format");
        }
        catch (NullPointerException nullPointer)
        {
        }
        scanner.close();
    }
}

Output:

Enter the number of nodes in the graph
6
Enter the adjacency matrix
0 1 0 0 0 0
0 0 1 1 0 0 
0 0 0 0 0 0 
0 0 0 0 1 0
0 0 0 0 0 1
0 0 1 1 0 0 
Enter the source for the graph
1
The Topological sort for the graph is given by 
TOPOLOGICAL SORT NOT POSSIBLE
 
Enter the number of nodes in the graph
6
Enter the adjacency matrix
0 1 0 0 0 1
0 0 1 1 0 0
0 0 0 0 0 0 
0 0 0 0 1 0
0 0 0 0 0 1
0 0 1 0 0 0
Enter the source for the graph
1
The Topological sort for the graph is given by 
1	2	4	5	6	3

Related posts:

Introduction to Java 8 Streams
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Java Program to Implement Self organizing List
Chương trình Java đầu tiên
Java Program to Implement Ternary Search Algorithm
JWT – Token-based Authentication trong Jersey 2.x
Different Ways to Capture Java Heap Dumps
Java Program to Implement Gabow Algorithm
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
Binary Numbers in Java
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Guava – Join and Split Collections
Allow user:password in URL
Java Program to implement Priority Queue
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Spring WebFlux Filters
Spring Security OAuth Login with WebFlux
Remove the First Element from a List
Using Spring @ResponseStatus to Set HTTP Status Code
Mix plain text and HTML content in a mail
Java – Combine Multiple Collections
An Example of Load Balancing with Zuul and Eureka
Java Program to Implement Aho-Corasick Algorithm for String Matching
Java Program to Implement Circular Doubly Linked List
Assert an Exception is Thrown in JUnit 4 and 5
Java Program to Generate Randomized Sequence of Given Range of Numbers
Java Program to Implement Leftist Heap
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Quick Guide to Spring Controllers
Retrieve User Information in Spring Security
Java Program to Perform Naive String Matching
Inheritance and Composition (Is-a vs Has-a relationship) in Java