码迷,mamicode.com
首页 > 其他好文 > 详细

Topological Sort

时间:2016-05-01 12:12:17      阅读:117      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!