C ++程序使用BFS检查图是否为二分图
二分图是其中可以使用两种颜色进行着色的图形,即:一组顶点的颜色相同。这是一个C++程序,用于检查是否使用BFS进行图形二分。
算法
Begin Function Bipartite(): 1) Assign a color to the source vertex 2) Color all the neighbors with another color except first one color. 3) Color all neighbor’s neighbor with First color. 4) Like this way, assign color to all vertices such that it satisfies all the constraints of k way coloring problem where k = 2. 5) While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices i.e.; graph is not Bipartite End
示例
#include <iostream>
#include <queue>
#define V 5
using namespace std;
bool Bipartite(int G[][V], int s) {
int colorA[V];
for (int i = 0; i < V; ++i)
colorA[i] = -1;
colorA[s] = 1; //Assign a color to the source vertex
queue <int> q; //Create a queue of vertex numbers and enqueue source vertex for BFS traversal
q.push(s);
while (!q.empty()) {
int w = q.front(); //dequeue a vertex
q.pop();
for (int v = 0; v < V; ++v) //Find all non-colored adjacent vertices {
if (G[w][v] && colorA[v] == -1) //An edge from w to v exists and destination v is not colored {
colorA[v] = 1 - colorA[w]; //Assign alternate color to this adjacent v of w
q.push(v);
} else if (G[w][v] && colorA[v] == colorA[w]) //An edge from w to v exists and destination
//v的颜色与u相同
return false;
}
}
return true; //if all adjacent vertices can be colored with alternate color
}
int main() {
int G[][V] = {{ 0, 1, 0, 0},
{ 1, 0, 0, 0},
{ 0, 0, 0, 1},
{ 1, 0, 1, 0}};
if (Bipartite(G, 0))
cout << "The Graph is Bipartite"<<endl;
else
cout << "The Graph is Not Bipartite"<<endl;
return 0;
}输出结果
The Graph is Bipartite
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短