递归不会停止

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。