gpt4 book ai didi

c - 在图中使用队列进行拓扑排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:14 24 4
gpt4 key购买 nike

下面是我读的关于队列的拓扑排序算法,写在课本上:

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);
}


}
}
}

下图的算法失败了:

graph the algorithm fails on

如果在给定的图中最初 7 5 3 的入度为零,那么它们将被插入到队列中,但是对于与 7 5 3 相邻的任何顶点,我们没有任何顶点度数 1。这意味着 if(--indegree[w]==0)7 5 3 不成立,因此队列中不会有进一步的排队,因此该算法将不会处理更多的顶点。 我想知道如果图是 DAG,为什么算法会失败?哪里不对?

我知道我们也可以使用 DFS 实现拓扑排序,但我想按原样实现以下内容:

the pseudocode of the algorithm I want to implement

最佳答案

您的算法实现不正确。这里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);
}
}
}
}

这适用于每个 DAG。

关于c - 在图中使用队列进行拓扑排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53202300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com