Topological Sort

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

 

posted on 2016-05-01 11:46  dingjunnan  阅读(379)  评论(0编辑  收藏  举报

导航