Graph: Topological Sort

利用和detect cycle类似的思路, 用dfs + recursion解决。并且一定时一个有向图。

Stack<Integer> stack = new Stack<>();
// 0:unvisit, 1:visited, 2:visiting
public boolean topologicalSort(Node node) {
    if(node.state = 2) return true;
    node.state = 2;
    if(map.get(node) != null) {
        for(Node adj : map.get(node)) {
            if(adj.state != 1 && topologicalSort(adj)) {
                return true;
            }
        }
    }
    node.state = 1;
    stack.push(node.val);
    return false;
}

本文固定链接: http://www.js-code.com/node-js/node-js_38432.html