TOPOLOGICAL-SORT(G)
1 call DFS(G) to compute finishing times v.f for each vertex v
2 as each vertex is finished, insert it onto the front of a linked list
3 return the linked list of verteces
java代码如下:
/**
* 拓扑排序
* @param graphContent
* @return
* @throws Exception
*/
public static LinkedList<Vertex> topo_sort(String graphContent) throws Exception{
if (hasLoop(graphContent)){
throw new Exception("this graph has loop");
}
LinkedList<Vertex> list = new LinkedList<Vertex>();
List<Vertex> vertexs = Route.getVertexs(graphContent);
for (Vertex vertex : vertexs){
vertex.setColor(Color.WHITE);
vertex.setParent(null);
}
for (Vertex vertex : vertexs){
if (vertex.getColor().equals(Color.WHITE)){
DFS_VISIT(graphContent, vertex, list);
}
}
return list;
}
/**
* 检查是否有环,没有含有入度为0的节点则必然有环
* @param graphContent
* @return
*/
@SuppressWarnings("rawtypes")
private static boolean hasLoop(String graphContent) {
// TODO Auto-generated method stub
List<Vertex> vertexs = Route.getVertexs(graphContent);
LinkedList[] lists = Route.getLinkedList(graphContent);
int count = 0;
for (Vertex vertex : vertexs){
for (LinkedList l : lists){
for (int i = 1; i < l.size(); i++){
if (vertex.equals(l.get(i))){
count++;
}
}
}
if (count == 0){
return false;
}else {
count = 0;
}
}
return false;
}
private static int time = 0;
@SuppressWarnings("rawtypes")
public static void DFS_VISIT(String graphContent, Vertex vertex, LinkedList<Vertex> list){
LinkedList[] lists = Route.getLinkedList(graphContent);
time = time + 1;
vertex.setS(time);
vertex.setColor(Color.GRAY);
for (Object v : lists[vertex.getID()]){
Vertex V = (Vertex)v;
if (V.getColor().equals(Color.WHITE)){
V.setParent(vertex);
DFS_VISIT(graphContent, V, list);
}
}
vertex.setColor(Color.BLACK);
time = time + 1;
vertex.setF(time);
list.addFirst(vertex);
}