二分图的判定(dfs+bfs)

上篇转发了关于二分图的概念啥的,这篇来说一下,二分图的染色法判定。

说一下思路吧。找寻所有没染色的顶点,染色,如果有发现相邻的连接点颜色相同了,则此构不成二分图。全部染色完且没有相邻结点颜色相同则为二分图。

分别用DFS和BFS分别书写。先献上DFS的代码并附有详解

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<vector>
using namespace std;
//first dfs实现。只用两种颜色,确定一种后,另外一种也就确定了
const int maxn = 520;
vector<int>G[maxn];
int color[maxn];
int V, E;
bool dfs(int v, int c)
{
	color[v] = c;
	for (int i = 0; i < G[v].size(); i++)
	{
		//G[v][i]顶点v通过边i连接的点
		if (color[G[v][i]] == c)//相邻点为c染色相同。不合题意。
			return false;
		if (color[G[v][i]] == 0 && !dfs(G[v][i], -c))//相邻点为染色,
                                                             //但却不能将他
                                                             //染为-c即还是c不合题意。
			return false;
	}
	return true;
}
int main()
{
	
	cin >> V >> E;
	memset(color, 0, sizeof(color));
	for (int i = 0; i < E; i++)
	{//输入各边连接情况
		int s, t;
		cin >> s >> t;
		G[s].push_back(t);
		G[t].push_back(s);
		//t向s以及s向t分别连边,此时G[s][t]的意义是由定点s的t边指向的顶点。

	}
	for (int i = 0; i < V; i++)
	{
		if (color[i] == 0)
		{
			if (!dfs(i, 1))
			{
				cout << "No" << endl;
				return 0;
			}
		}
	}
	cout << "Yes" << endl;
	return 0;
}

BFS代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
#include<queue>
#include<math.h>
#include<vector>
using namespace std;
const int maxn = 520;
int color[maxn];
int V, E;
vector<int>G[maxn];
//0和1为不同颜色
int bfs()
{
	memset(color, 0, sizeof(color));
	int x = 1;//从点1开始。
	queue<int>que;
	que.push(x);
	color[x] = 1;
	while (!que.empty())
	{
		int v = que.front();
		que.pop();
		for (int i = 0; i < G[v].size(); i++)
		{
			int y = G[v][i];
			if (color[y] == 0)
			{
				
				color[y] = -color[v];
				que.push(y);
			}
			else {
				if (color[v] == color[y])
				{
					cout << "No" << endl;
					return 0;
				}
			}
		}
	}
	cout << "Yes" << endl;
	return 0;
}
int main()
{
	cin >> V >> E;
	for (int i = 0; i < E; i++)
	{
		int s, t;
		cin >> s >> t;
		G[s].push_back(t);
		G[t].push_back(s);
	}
	bfs();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/fighting_yifeng/article/details/81635749