Graph.java 文件源码

java
阅读 25 收藏 0 点赞 0 评论 0

项目:codebuff 作者:
/** DFS-based topological sort.  A valid sort is the reverse of
 *  the post-order DFA traversal.  Amazingly simple but true.
 *  For sorting, I'm not following convention here since ANTLR
 *  needs the opposite.  Here's what I assume for sorting:
 *
 *    If there exists an edge u -> v then u depends on v and v
 *    must happen before u.
 *
 *  So if this gives nonreversed postorder traversal, I get the order
 *  I want.
 */
public List<T> sort() {
    Set<Node<T>> visited = new OrderedHashSet<Node<T>>();
    ArrayList<T> sorted = new ArrayList<T>();
    while ( visited.size() < nodes.size() ) {
        // pick any unvisited node, n
        Node<T> n = null;
        for (Node<T> tNode : nodes.values()) {
            n = tNode;
            if ( !visited.contains(n) ) break;
        }
        if (n!=null) { // if at least one unvisited
            DFS(n, visited, sorted);
        }
    }
    return sorted;
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号