用dfs来做,如果dfs的下一个没访问过,则给其涂上 和相连相反的,如果访问过,则判断其颜色是否和其相连的相同
AC代码:
#include<iostream>
using namespace std;
const int N = 200 + 5;
int G[N][N];
int vis[N];
int color[N];
int m,n;
bool ok;
void init () {
for (int i = 0 ; i < N ;i++) {
for (int j = 0 ; j < N ;j++) {
G[i][j] = 0;
}
vis[i] = 0;
color[i] = 0 ;
}
ok = true;
}
void colorclear() {
for (int i = 0;i < m ;i++) {
if (vis[i])
color[i] = 0;
}
}
void dfs (int x,int Color) {
if (vis[x] == 1 && color[x] == Color &&color[x] != 0) {
ok = false;
return;
}
if (vis[x] == 1)
return ;
vis[x] = 1;
color[x] = -Color;
for (int i = 0; i < m ;i++) {
if (G[x][i])
dfs(i,color[x]);
}
}
int main () {
int sta,en;
while (cin >> m) {
init();
if (!m)
break;
cin >> n;
for (int i = 0 ; i < n ;i++) {
cin >> sta;
cin >> en;
G[sta][en] = 1;
color[sta] = 1;
color[en] = 1;
}
for (int i = 0 ; i < m ; i++ )
for (int j = 0; j < n ; j++) {
if (G[i][j] && !vis[i]) {
dfs(i ,-color[i]);
colorclear();
}
}
if (ok == true)
cout <<"BICOLORABLE."<<endl;
else
cout <<"NOT BICOLORABLE."<<endl;
}
return 0;
}