Topological Sort

Build the Topological Sequence

Use node to build the dependency. You can also use map or other data structure.

class Node {
    int val;
    Set<Node> next; //current node has higher priority than next
    Node(int val) {
        this.val = val;
        next = new HashSet<>();
    }
}
public List<Node> topologicalSort(Set<Node> nodeSet) {
    Set<Node> visited = new HashSet<>();
    List<Node> ls = new LinkedList<>();
    for(Node n: nodeSet) helper(visited,n,ls);
    return ls;
}

private void helper(Set<Node> visited, Node root, List<Node> ls) {
    if(visited.contains(n)) return;
    visited.add(root);
    for(Node n: root.next) {        
        helper(visited,n,ls);
    }
    ls.add(0,root); // or add to end and reverse the final result in topologicalSort
}

Detect if a graph is a Directed Acyclic Graph (DAG):

DFS Solution

BFS Solution (unchecked)

Use in degree.

Output all possible sequence (tested)

Last updated