Topological Sort Algorithm

Teja IllaTeja Illa
1 min read

Topological sort algorithm using DFS

import java.util.*;

public class Main {

  public static class Graph {
    int v;
    int e;

    List<List<Integer>> arrList;

    public Graph(int v, int e) {
      this.v = v;
      this.e = e;

      arrList = new ArrayList<>();

      for(int i=0; i<v; i++) {
        arrList.add(new ArrayList<>());
      }
    }

    public void addEdge(int start, int end) {
      arrList.get(start).add(end);
    }

    public void runTopologicalSort(int source) {

      Stack<Integer> stk = new Stack<>();
      int[] visited = new int[v];


      topologicalSortHelper(source, stk, visited);

      for(int i=0; i< v; i++) {
        if(visited[i] == 0) {
          topologicalSortHelper(i, stk, visited);
        }
      }

      while(!stk.isEmpty()) {
        System.out.println(stk.pop());
      }
    }

    public void topologicalSortHelper(int source, Stack<Integer> stk, int[] visited) {

      visited[source] = 1;
      List<Integer> adjList = arrList.get(source);

      for(Integer adjVer : adjList) {
        if(visited[adjVer] == 0) {
          topologicalSortHelper(adjVer, stk, visited);
        }
      }

      stk.add(source);
    }
  }

  public static void main(String[] args) {

    Graph g = new Graph(6, 6);

    g.addEdge(5, 0);
    g.addEdge(4, 0);
    g.addEdge(5, 2);
    g.addEdge(4, 1);
    g.addEdge(2, 3);
    g.addEdge(3, 1);

    g.runTopologicalSort(0);

  }
}
0
Subscribe to my newsletter

Read articles from Teja Illa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Teja Illa
Teja Illa