我正在实现一个算法来确定一个无向图是否是二分的。基于this pseudo-code使我的实现,它适用于图形连接,但是当它断开时,只是程序指出了一个错误的答案。我认为如果它没有连接,那么每个不相交的子图就需要一个循环。但我坚持这一点。我怎样才能解决我的代码,让我打印出正确的答案?BFS检查一个图是否在C++中是二分的
#include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
#define MAX 1000
int numberVertex, numberEdges;
int particion[MAX], visited[MAX];
vector<int> adjacencyMatrix[MAX];
bool bfs()
{
int i, origin, destination, begin;
queue<int> queueVertex;
begin = 0;
queueVertex.push(begin);
particion[begin] = 1; // 1 left,
visited[begin] = 1; // set adjacencyMatrixray
while(!queueVertex.empty())
{
origin = queueVertex.front(); queueVertex.pop();
for(i=0; i < adjacencyMatrix[origin].size(); i++)
{
destination = adjacencyMatrix[origin][i];
if(particion[origin] == particion[destination])
{
return false;
}
if(visited[destination] == 0)
{
visited[destination] = 1;
particion[destination] = 3 - particion[origin]; // alter 1 and 2 subsets
queueVertex.push(destination);
}
}
}
return true;
}
int main()
{
freopen("tarea2.in", "r", stdin);
int i,j, nodeOrigin, nodeDestination;
scanf("%d %d", &numberVertex, &numberEdges);
for(i=0; i<numberEdges; i++)
{
scanf("%d %d", &nodeOrigin, &nodeDestination);
adjacencyMatrix[nodeOrigin].push_back(nodeDestination);
adjacencyMatrix[nodeDestination].push_back(nodeOrigin);
}
if(bfs()) {
printf("Is bipartite\n");
for (j=0; j<numberVertex; j++){
cout<<j<<" "<<particion[j]<<endl;
}
}
else {printf("Is not bipartite\n");}
return 0;
}
例如,对于此输入
6 4
3 0
1 0
2 5
5 4
输出应该是:
Is bipartite
0 1
1 2
2 1
3 2
4 1
5 2
而是抛出我的输出:
0 1
1 2
2 0
3 2
4 0
5 0
这是因为该图是不是连接图,即有两个连接的组件。我希望你能帮助我,因为我一直坚持这几天。
伟大的代码,很好地完成。 – bappi48 2015-07-03 04:59:57