二分图判定 dfs

#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();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值