【发布时间】:2021-03-15 08:39:23
【问题描述】:
函数定义为:
// DFS algorithm
void Graph::DFS(int current) {
visited[current] = true;
cout<<current << " ";
for (int u : adjLists[current])
if (!visited[u])
DFS(u);
}
// BFS algorithm
void Graph::BFS(void){
for(int i=0;i<numVertices;++i)
visited[i] = false;
list<int> q;
q.push_back(0);
visited[0] = true;
while(!q.empty())
{
int u = q.front();
q.pop_front();
cout<< u << " ";
for( int i : adjLists[u])
if(!visited[i]){
q.push_back(i);
visited[i] = true;
}
}
}
DFS 工作正常,无需使用 for 循环将访问数组的每个元素分配为等于 false,但 BFS 不是。为什么?
整个程序代码是-https://hastebin.com/ojuyogexof.cpp
【问题讨论】:
-
对我来说听起来像undefined behaviour。尝试先调用 BFS,然后查看 DFS 是否有效。有时糟糕的程序即使很糟糕也能奏效。这就是未定义行为的工作原理。
-
@john 是的,你是对的,首先调用 BFS DFS 无法正常工作。所以我需要为这两个函数使用 for 循环(但是我怎么能因为 DFS 是递归的)?
-
您需要有一个函数,通过将访问数组设置为 false 然后调用递归函数来开始深度优先搜索。
-
@john 很好,现在一切都搞定了 :)
标签: c++ algorithm graph depth-first-search breadth-first-search