Programming Algorithm-bipartite graph judgment code (c)

Source: Internet
Author: User
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








Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.