码迷,mamicode.com
首页 > 其他好文 > 详细

Geeks - Check whether a given graph is Bipartite or not 二分图检查

时间:2014-06-22 18:35:43      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   color   

检查一个图是否是二分图的算法

使用的是宽度搜索:

1 初始化一个颜色记录数组

2 利用queue宽度遍历图

3 从任意源点出发,染色0, 或1

4 遍历这点的邻接点,如果没有染色就染色与这个源点相反的颜色,如果已经染色并且和源点的值相反,那么就是合法点,如果是相同的颜色,那么就不能是二分图

 

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

#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";
	}
};


Geeks - Check whether a given graph is Bipartite or not 二分图检查,布布扣,bubuko.com

Geeks - Check whether a given graph is Bipartite or not 二分图检查

标签:style   class   blog   code   http   color   

原文地址:http://blog.csdn.net/kenden23/article/details/32321529

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!