gpt4 book ai didi

algorithm - 如何找到图循环中的顶点

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

例如。对于 1->2、2->3、3->4、4->2,我想打印 2、3、4。我尝试了 DFS,当我发现我之前访问过的顶点时,我会去父级直到我没有得到这个顶点,但是它不能很好地工作。有时会进入死循环。

运行 dfs:

int i;
for (i = 0; i < MAX_VER; i += 1)
if (ver[i].v == 0 && ver[i].nb > 0)
dfs(i);

dfs:

ver[v].v = 1;

int i;
for (i = 0; i < ver[v].nb; i += 1) {
ver[ver[v].to[i]].p = v;

if (ver[ver[v].to[i]].v == 0)
dfs(ver[v].to[i]);
else
// cycle found
printCycle(ver[v].to[i]);
}

和打印周期:

printf("\cycle: %d ", v);

int p = ver[v].p;

while (p != v) {
printf("%d(%d) ", p, v);

p = ver[p].p;
}

printf("\n");

顶点结构:

int *to; // neighbor list

int nb; // how many neighbor
int p; // parent
short v; // was visited? 0 = false, 1 = true

最佳答案

听起来您正在寻找“强连通分量”——所以您很幸运,有一个众所周知的算法可以在图中找到这些分量。参见 Tarjan .

该算法在那篇文章中描述得很好,但是它有点冗长,所以我不会在这里粘贴它。此外,除非您这样做是为了学习,否则使用现有的实现可能会更好,实现起来并不难,但也容易。

编辑。看起来这个问题实际上是一个骗局......我很难说这个但它可能需要关闭,抱歉。参见 Best algorithm for detecting cycles in a directed graph

关于algorithm - 如何找到图循环中的顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427972/

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