Maintain two boolean array visited and visiting, where visited mean a node has been visited from a path in dfs, while visiting means a node is being visited in the dfs
If the visiting value for a node is true, this means a loop is found
If the visited value for a node is true, this means we have visited this node, we can skip it
importjava.util.*;publicstaticvoidtopologicalSortByDFS(int nodes,int[][] edges) {List<List<Integer>> adjList =newArrayList<>();List<Integer> topologicalSortOrder =newArrayList<>();for (int i =0; i < nodes; i++) {adjList.add(newArrayList<>()); }for (int[] edge : edges) {adjList.get(edge[0]).add(edge[1]); }boolean[] visited =newboolean[nodes];boolean[] visiting =newboolean[nodes];for (int i =0; i < nodes; i++) {if (!dfs(i, visited, visiting, adjList, topologicalSortOrder)) {System.out.println("Cycle is detected, can not implement topological sort");return; } }printTopologicalSortOrder(topologicalSortOrder); }publicstaticbooleandfs(int curNode,boolean[] visited,boolean[] visiting,List<List<Integer>> adjList,List<Integer> topologicalSortOrder) {// if curNode has been visited (added to the result), we skip itif (visited[curNode]) {returntrue; }// Found loop in the current DFSif (visiting[curNode]) {returnfalse; } visiting[curNode] =true;for (int nextNode :adjList.get(curNode)) {if (!dfs(nextNode, visited, visiting, adjList, topologicalSortOrder)) {returnfalse; } } visited[curNode] =true;topologicalSortOrder.add(0, curNode);returntrue; }publicstaticvoidprintTopologicalSortOrder(List<Integer> list) {System.out.println("Topological Sort: ");for (int order : list) {System.out.print(order +" "); } }publicstaticvoidmain(String[] args) {int nodes =6;int[][] edges = {{5,2}, {5,0}, {4,0}, {4,1}, {2,3}, {3,1}};topologicalSortByDFS(nodes, edges); }
2. Thoughts
Q:What if the input is not integer, but rather character or string, what data structure should we use to build up adjacent list and inDegree?
A: Use hashmap, for example, if the input is character, then Adjacent list: Map<Character, Set<Character>>, inDegree: Map<Character, Integer>
Q: Time Complexity for Topological Sort:
A: O(n + e), where n is the number of nodes and e is the number of edges