首页 > 代码库 > BFS判断是否是二分图Bipartite算法
BFS判断是否是二分图Bipartite算法
二分图bipartite
使用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"; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。