• Geeks


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

    使用的是宽度搜索:

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


  • 相关阅读:
    个人作业Week2-代码复审
    个人项目-数独
    个人作业-Week1
    第零次个人作业
    mysql统计某个指标之和大于指定值的记录
    Redis命令行查询缓存值
    Grep命令
    Log4j配置文件中指定日志路径
    Cadence OrCAD17.2禁止和启用start page的设置方法
    Linux内核实现透视---kthread_work
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/6748007.html
Copyright © 2020-2023  润新知