BFS判断是否是二分图Bipartite算法

时间:2014-06-01 15:03:24   收藏:0   阅读:288

二分图bipartite

bubuko.com,布布扣

使用BFS广度优先判断一个图是否是二分图。基本图操作。

参考

http://www.geeksforgeeks.org/bipartite-graph/

#pragma once
#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;

class CheckwhetheragivengraphisBipartiteornot
{
	const static int V = 4;
	bool isBipartite(int G[][V], int src)
	{
		int colors[V];
		fill(colors, colors+V, -1);

		colors[src] = 1;

		queue<int> qu;
		qu.push(src);
		while (qu.size())
		{
			int u = qu.front();
			qu.pop();

			for (int v	= 0; v < V; v++)
			{
				if (G[u][v] && colors[v] == -1)
				{
					colors[v] = 1 - colors[u];
					qu.push(v);
				}
				else if (G[u][v] && colors[v] == colors[u]) return false;
			}
		}
		return true;
	}
public:
	CheckwhetheragivengraphisBipartiteornot()
	{
		int G[][V] = 
		{
			{0, 1, 0, 1},
			{1, 0, 1, 0},
			{0, 1, 0, 1},
			{1, 0, 1, 0}
		};

		isBipartite(G, 0) ? cout << "Yes" : cout << "No";
	}
};



BFS判断是否是二分图Bipartite算法,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!