#include<stdio.h>
#include <iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<string>
const int maxn = 100 + 5;
using namespace std;
vector<int>G[maxn];//vector数组实现图
int color[maxn];//顶点的颜色 1 or -1
int v;//顶点数
bool dfs(int v, int c) {
color[v] = c;
for (int i= 0;i < G[v].size();i++) {
if (color[G[v][i]] == c)return false;// 相邻顶点同色
if (color[G[v][i]] == 0 && !dfs(G[v][i], -c))return false;
//注意递归调用的实参为-c,保证相邻点涂上不同的颜色
}return true;
}
void solve() {
for (int i = 0;i < v;i++) {
if (color[i] == 0) {//第二次触发则说明该顶点与上一次触发的顶点不连通
if (!dfs(i, 1)) {
printf("NO\n");return;
}
}
}
printf("YES\n");
}
int main()
{
v = 4;
G[0].push_back(1);G[0].push_back(3);
G[1].push_back(0);G[1].push_back(2);
G[2].push_back(1);G[2].push_back(3);
G[3].push_back(0);G[3].push_back(2);
solve();
v = 6;
G[4].push_back(5);G[5].push_back(4);//无向图需要正反都push
solve();
v = 7;
G[6].push_back(4);G[4].push_back(6);
G[6].push_back(5);G[5].push_back(6);
solve();
G[2].push_back(4);G[4].push_back(2);
solve();
}
二分图判定 dfs
猜你喜欢
转载自blog.csdn.net/hanker99/article/details/84105067
今日推荐
周排行