【发布时间】:2012-07-03 14:33:31
【问题描述】:
我是图论的新手。假设有一个连通无向图。我想知道它是否有一个奇数长度的循环。我可以使用 BFS 找到我的图表中是否存在循环。我还没学过DFS。这是我的代码,它只是查找是否存在循环。提前致谢。
#include<iostream>
#include<vector>
#include<queue>
#include<cstdio>
#define max 1000
using namespace std;
bool find_cycle(vector<int> adjacency_list[]);
int main(void)
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int vertex, edge;
vector<int> adjacency_list[max];
cin >> vertex >> edge;
//Creating the adjacency list
for(int i=1; i<=edge; i++)
{
int n1, n2;
cin >> n1 >> n2;
adjacency_list[n1].push_back(n2);
adjacency_list[n2].push_back(n1);
}
if(find_cycle(adjacency_list))
cout << "There is a cycle in the graph" << endl;
else cout << "There is no cycle in the graph" << endl;
return 0;
}
bool find_cycle(vector<int> adjacency_list[])
{
queue<int> q;
bool taken[max]= {false};
int parent[max];
q.push(1);
taken[1]=true;
parent[1]=1;
//breadth first search
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=0; i<adjacency_list[u].size(); i++)
{
int v=adjacency_list[u][i];
if(!taken[v])
{
q.push(v);
taken[v]=true;
parent[v]=u;
}
else if(v!=parent[u]) return true;
}
}
return false;
}
【问题讨论】:
-
提示:一个图没有奇数循环当且仅当它是2-colorable。
-
@AdamRosenfield,非常感谢。
-
@AdamRosenfield,我应该搜索整个图还是只搜索包含循环的子图。因为图中可以有不止一个循环。
-
这对于你扔给它的每个图表是否都返回 true?
-
@Wug,对于无向图和连通图,它应该返回 true。但我还没有检查所有棘手的情况。
标签: c++ algorithm graph cycle breadth-first-search