递归不会停止
Recursion does not stop
本文关键字:递归 更新时间:2023-10-16
我正在编写使用 DFS 算法在图中查找周期的代码。然而,当我去打印循环的路径时,发生了一些非常奇怪的事情。在评论中阅读我的担忧。
#include <iostream>
#include "graph.h"
#include <stdio.h>
using namespace std;
int discovered[MAXV+1];
int parent[MAXV+1];
//Printing path that contains the cycle
void find_path(int start, int end)
{
int s = start;
int e = end;
while(s != e)
{
cout<<s<<" ";
s = parent[s];
}
/*The loop above does not stops ;
which means the condition parent[s] == e ;
does not meet . However , on printing out the
values of s , parent[s] , and e , on successive iteration
I can see that the value of parent[s] and e becomes
equal after a certain time , even though the loop does not
terminate.
*/
}
void dfs(graph *g , int start)
{
int dis = 1;
int u = 0 ;
edgenode *p;
p = g->edges[start];
discovered[start] = dis;
while(p!= NULL)
{
u = p->y;
parent[u] = start;
if(discovered[u]== 1){ cout<<"Cycle"<<start<<u<<endl; find_path(start,u);}
else dfs(g,u);
p = p->next;
}
discovered[start] = dis +1;
printf("n");
}
int main()
{
for(int i= 1; i<=MAXV+1; i++)
{
discovered[i] = false;
parent[i] = -1;
}
graph *g = new graph();
read_graph(g,true);
dfs(g,1);
}
那么,我的逻辑调用上述递归是否有缺陷,或者我的g++编译器行为怪异。任何细读我的代码将不胜感激。谢谢。
P.S:你可以假设我已经实现了一个图结构,我在编译时合并了它。我假设您对BFS算法的实现有一个很好的了解。如果您对理解代码有任何顾虑,请告诉我。
dfs
中的算法已损坏。当它检查节点 1 的边时,它会找到从节点 1 到节点 2 的边,并将 1 标记为 2 的父级。稍后,它找到从节点 5 到节点 2 的边,并将 5 标记为 2 的父级,替换parent
数组中的前一个条目。
后来,当它确定有一个从 1 到 5(到 1)的循环时,它会调用 find_path(5, 1)
。但是,find_path
永远找不到节点 1,因为跟随父节点从 5 导致 4、3、2,然后再回到 5。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败