判断二分图的办法是:是否能只用2种颜色给一整张图没有矛盾的上色(同一条边的两种颜色不同)。
代码:
对一个节点进行dfs,并且给它上色1,如果其子节点和它颜色相同就说明不是二分图。如果其子节点的上相反的颜色-1出现冲突,那么仍然不是二分图。
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
using namespace std;
const int N = 3005;
int n, m; //n个节点 m条边
vector<int> map[N];
int color[N];
bool dfs (int v, int c) {
color[v] = c;
for (int i = 0; i < map[v].size(); i++) {
if (color[map[v][i]] == c) {
return 0;
}
if (color[map[v][i]] == 0 && !dfs(map[v][i], -c)) {
return 0;
}
}
return 1;
}
int main () {
for (int i = 0; i < N; i++) {
map[i].clear();
}
memset(color, 0, sizeof(color));
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d %d", &a, &b);
map[a].push_back(b);
map[b].push_back(a);
}
if (dfs(0, 1)) {
cout << "yes" << endl;
}
else {
cout << "no" << endl;
}
return 0;
}