1. 程式人生 > >二分圖判定 dfs

二分圖判定 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();
}