Definition
Topological sorting is useful in situations in which items or events must be arranged in a specific order. For example, topological sorting can model job scheduling.Modeling job schedules with graphs is called critical path analysis(关键路线分析CPI).
The above figure adjacent matrix:
For a directed graph, the method that adds an edge thus needs only a single statement,
public void addEdge(int start, int end) // directed graph
{
adjMat[start][end] = 1;
}
The topological sorting algorithm
The idea behind the topological sorting algorithm is unusual but simple. Three steps are necessary:
1) Find a vertex that has no successors.
The successors to a vertex are those vertices that are directly “downstream” from it—that is, connected to it by an edge that points in their direction. If there is an edge pointing from A to B, then B is a successor to A.
2) Delete this vertex from the graph, and insert its label at the end of a list.
3) Step1 and step2 are repeated until all the vertices are gone. At this point, the list shows the vertices arranged in topological order.
Deleting is the heart of the algorithm. The algorithm works because if a vertex has no successors, it must be the last one in the topological ordering.
The topological sorting algorithm works on unconnected graphs(非连通图) as well as connected graphs(连通图). One kind of graph the topological-sort algorithm cannot handle is a graph with cycles.A topo