[英]How do I pass a continously decreasing variable in recursion ? [C++]
我正在尝试解决https://uva.onlinejudge.org/external/3/336.pdf中指定的节点太远的问题。 我正在尝试为此使用深度优先搜索(DFS)。 但是我找不到答案。 我正在为DFS使用递归,并且已将参数ttl
传递给函数DFS
。 据我所知,每次连续递归都需要减少ttl
,但是碰巧每次递归都会递减。 这是代码:-
#include<iostream>
#include<list>
#include<stdio.h>
using namespace std;
class Graph
{
int V;
list<int> *adj;
public:
Graph(int V);
void addEdge(int v, int w);
void DFSUtil(int v, bool visited[], int ttl);
void DFS(int s, int ttl);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
void Graph::DFSUtil(int v, bool visited[], int ttl)
{
visited[v] = true;
cout << endl;
int k = ttl;
if(k>=0)
{
cout << ttl << " " << v ;
list<int>::iterator i;
for(i = adj[v].begin(); i!=adj[v].end(); ++i)
{
if(!visited[*i])
{
int b = ttl - 1;
DFSUtil(*i, visited, b);
}
}
}
}
void Graph::DFS(int s, int ttl)
{
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
{
visited[i] = false;
}
DFSUtil(s, visited,ttl);
}
int main()
{
Graph g(100);
int nc;
while(scanf("%d",&nc))
{
if(nc == 0)
{
break;
}
for(int i = 0; i < nc; i++)
{
int v, w;
cin >> v >> w;
g.addEdge(v, w);
}
int s, ttl;
while(scanf("%d%d",&s,&ttl))
{
if(s == 0 && ttl == 0)
{
break;
}
g.DFS(s, ttl);
}
}
return 0;
}
输入为:-
16
10 15 15 20 20 25 10 30 30 47 47 50 25 45 45 65
15 35 35 55 20 40 50 55 35 40 55 60 40 60 60 65
35 2 35 3 0 0
0
输出是:-
2 35
1 15
0 10
0 20
1 55
0 50
0 60
那么,如何传递ttl使其仅针对相应的递归调用递减?
编辑:-这个问题在我看来也模棱两可。 它说在任何一对节点之间最多只能有一条(直接)通信线路。 但是,根据输出,它表明该图是无向的。
编辑:-我编辑了代码,并给出了给定的输出。 问题在于节点35的边为40,节点60的边也为40。当递归进行到60时,它访问40,但是由于ttl
> 0,所以它不会被打印。 但是由于35具有40的边缘,因此应该将其打印出来。 这就是我卡住的地方。
看来问题不在于ttl。 虽然应该有一个终止声明,例如
if(ttl<0)
return;
但是主要的问题是-由于数组是通过地址传递的,因此访问的数组仍会通过连续递归进行修改。 因此,一旦它尝试遍历for循环,由于先前的递归而被访问的数组将被修改。 假设,如果有3个节点,并且边为1 2、1 3、23。则如果给定node和ttl为1 3,则它基本上应为-
1-> 2-> 3,1-> 3-> 2。
但是在这种代码情况下,由于在第一种情况下1-> 2-> 3,它已经遍历了3,所以visited [3]变为true,导致它在下一次迭代中跳过3。 因此,它仅给出1-> 2-> 3。
解决方案是代替array,您可以使用Vector使它按值传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.