Bipartite Graph judgment code (c)
Address: http://blog.csdn.net/caroline_wendy
Question: Given a graph with n vertices, We need to dye each vertex on the graph and make the adjacent vertex colors different.
Whether the color can be stained in up to two colors. No duplicate edges or closed loops exist.
That isBipartite Graph Problems.
UseDeep Priority Search (DFS), Dye the vertex into C, and then the adjacent edge into-C.
If the adjacent edges are dyed and the same, the graph is not a bipartite graph. If all edges are colored and different, the graph is a bipartite graph.
Search multiple times to avoidNon-Connected Graph.
Code:
/* * CppPrimer.cpp * * Created on: 2014.7.27 * Author: Caroline *//*eclipse cdt*/#include <stdio.h>#include <vector>using namespace std;class Program {static const int MAX_V = 100;/*vector<int> G[MAX_V] = {{1,3}, {0,2}, {1,3}, {0,2}};int V = 4;*/vector<int> G[MAX_V] = {{1,2}, {0,2}, {0,1}};int V = 3;int color[MAX_V] = {0};bool dfs(int v, int c) {color[v] = c;for (size_t i=0; i<G[v].size(); ++i) {if (color[G[v][i]] == c) return false;if (color[G[v][i]] == 0 && !dfs(G[v][i], -c)) return false;}return true;}public:void solve() {for (int i=0; i<V; i++) {if (color[i] == 0) {if(!dfs(i,1)) {printf("result = No\n");return;}}}printf("result = Yes\n");}};int main (void){Program iP;iP.solve();return 0;}
Output:
result = No