首页 > 其他 > 详细

Topological Sort

时间:2016-05-01 12:11:58      阅读:287      评论:0      收藏:0      [点我收藏+]

In what kind of situation will we need to use topological sort?

Precedence(优先级) scheduling, say given a set of tasks to be completed with precedence constraints, in which order should we schedule the tasks? One simple example are classes in university, you need to take introduction to computer science before you take advanced programming, so this is the constraint, you need to do A before you do B, now I give you many tasks, and they have many constraints, in what kind of order should you do these tasks?

Where does topological sort come from?

It comes from Digraph Processing, because this kind of problem can be modeled as a DiGraph, vertex = task, edge = precedence constraint.

Limitation

Topological Sort only exists in DAG(Directed Acyclic Graph), so you need to run a DFS first to make sure that the graph is a DAG.

Algorithm

1, Run depth-first search

2, Return vertices in reverse postorder

Reverse DFS postorder of a DAG is a topological order

Code

技术分享
public class DepthFirstOrder
{
    private boolean[] marked;
    private Stack<Integer> reversePost;
    
    public DepthFirstOrder(Digraph G)
    {
        reversePost = new Stack<Integer>();
        marked = new Boolean[G.V()];
        for (int v = 0; v < G.V(); v++)
        {
            if (!marked[v])
            {
                dfs(G, v);
            }
        }
    }

    private void dfs(Digraph G, int v)
    {
        marked[v] = true;
        for (int w : G.adj(v))
        {
            if (!marked[w])
            {
                dfs(G, w);
            }
        }
        reversePost.push(v);
    }
    
    public Iterable<Integer> reversePost()
    {
        return reversePost;
    }
}
View Code

 

Topological Sort

原文:http://www.cnblogs.com/dingjunnan/p/5450250.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!