无向图代码中检测循环错误
Error in detecting cycle in undirected graph code
#include<bits/stdc++.h>
using namespace std;
bool iscycle(list<int> *adj,bool *visited,int i,int parent){
visited[i] = true;
for(auto j : adj[i]){
if(!visited[j])
if(iscycle(adj,visited,j,i))
return true;
else if(j != parent)
return true;
}
return false;
}
bool solve(vector<vector<int>> vect,int v){
list<int> *adj = new list<int>[v];
int i;
for(i = 0;i < vect.size();i++){
adj[vect[i][0]].push_back(vect[i][1]);
adj[vect[i][1]].push_back(vect[i][0]);
}
bool *visited = new bool[v];
for(i = 0;i < v;i++)
visited[i] = false;
int parent = -1;
for(i = 0;i < v;i++)
if(!visited[i]){
parent = -1;
if(iscycle(adj,visited,i,parent))
return true;
}
return false;
}
int main(){
std::vector<vector<int>> vect{{0,1},{1,2},{2,3}};
cout<<solve(vect,4)<<endl;
return 0;
}
这段检测无向图中循环的代码在某些测试用例上失败,例如当有 4 个顶点并且每两个顶点按向量“vect”指定连接时。对于这个特定的测试用例,答案应该是 0(即没有检测到循环)但生成的答案代码是 1。我不明白错误是什么。
iscycle
中的 else
与第二个,最里面的 if
,而不是第一个,尽管有误导性缩进。根据需要添加大括号。
#include<bits/stdc++.h>
using namespace std;
bool iscycle(list<int> *adj,bool *visited,int i,int parent){
visited[i] = true;
for(auto j : adj[i]){
if(!visited[j])
if(iscycle(adj,visited,j,i))
return true;
else if(j != parent)
return true;
}
return false;
}
bool solve(vector<vector<int>> vect,int v){
list<int> *adj = new list<int>[v];
int i;
for(i = 0;i < vect.size();i++){
adj[vect[i][0]].push_back(vect[i][1]);
adj[vect[i][1]].push_back(vect[i][0]);
}
bool *visited = new bool[v];
for(i = 0;i < v;i++)
visited[i] = false;
int parent = -1;
for(i = 0;i < v;i++)
if(!visited[i]){
parent = -1;
if(iscycle(adj,visited,i,parent))
return true;
}
return false;
}
int main(){
std::vector<vector<int>> vect{{0,1},{1,2},{2,3}};
cout<<solve(vect,4)<<endl;
return 0;
}
这段检测无向图中循环的代码在某些测试用例上失败,例如当有 4 个顶点并且每两个顶点按向量“vect”指定连接时。对于这个特定的测试用例,答案应该是 0(即没有检测到循环)但生成的答案代码是 1。我不明白错误是什么。
iscycle
中的 else
与第二个,最里面的 if
,而不是第一个,尽管有误导性缩进。根据需要添加大括号。