new*_*wby 0 c sorting algorithm graph-theory depth-first-search
下面是我对队列拓扑排序算法的阅读,写在我的教科书中:
void topologicalsort(struct Graph* G){
struct queue* Q;
int counter;
int v,w;
Q=createqueue();
counter=0;
for(v=0;v<G->V;v++){
if(indegree[v]==0)
enqueue(Q,v);
while(!isemptyqueue(Q)){
v=dequeue(Q);
topologicalorder[v]=++counter;
for each w to adjacent to v
if(--indegree[w]==0){
enqueue(Q,w);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于下图,该算法失败:
如果在给定的图中最初 7 5 3 的入度为零,那么它们将被插入到队列中,但是对于与7 5 3
我们相邻的任何顶点,我们都没有任何度为 1 的顶点。这意味着这if(--indegree[w]==0)
将不成立,7 5 3
因此有将不会在队列内进一步排队,因此该算法将不会处理更多的顶点。如果图形是 DAG,我想知道为什么算法会失败?哪种方式不正确?
我知道我们也可以使用 DFS 实现拓扑排序,但我想按原样实现以下内容:
您的算法实现不正确。这里while(!isemptyqueue(Q))
不在for(v=0;v<G->V;v++)
(参见算法中的缩进)。有关更多说明,请参见下文:
void topologicalsort(struct Graph* G){
struct queue* Q;
int counter;
int v,w;
Q=createqueue();
counter=0;
for(v=0;v<G->V;v++){
if(indegree[v]==0)
enqueue(Q,v);
}
while(!isemptyqueue(Q)){
v=dequeue(Q);
topologicalorder[v]=++counter;
for each w to adjacent to v {
if(--indegree[w]==0){
enqueue(Q,w);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于每个 DAG。