[email protected] Check whether a given graph is Bipartite or not

Check whether a given graph is Bipartite or not

Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, or u belongs to V and v to U. We can also say that there is no edge that connects vertices of same set.

A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with even cycle using two colors. For example, see the following graph.

It is not possible to color a cycle graph with odd cycle using two colors.

Algorithm to check if a graph is Bipartite:
One approach is to check whether the graph is 2-colorable or not using backtracking algorithm m coloring problem.
Following is a simple algorithm to find out whether a given graph is Birpartite or not using Breadth First Search (BFS).
1. Assign RED color to the source vertex (putting into set U).
2. Color all the neighbors with BLUE color (putting into set V).
3. Color all neighbor’s neighbor with RED color (putting into set U).
4. This way, assign color to all vertices such that it satisfies all the constraints of m way coloring problem where m = 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 (or graph is not Bipartite)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<limits>
#include<vector>
#include<stack>
using namespace std;
struct edge{
    int to, cost;
    edge(int t){
        this->to = t; this->cost = 0;
    }
};
void addEdge(vector<edge> &, vector<vector<int> > &, int, int);//add directed edge.
void buildMap(vector<edge> &edgelist, vector<vector<int> > &G){
    addEdge(edgelist,G,0,1);
    addEdge(edgelist,G,1,2);
    addEdge(edgelist,G,2,3);
    addEdge(edgelist,G,3,4);
    addEdge(edgelist,G,4,0);
    //addEdge(edgelist,G,5,0);
}
void addDoubleEdge(vector<edge> &, vector<vector<int> > &, int, int);// add undirected edge.
bool isCyclic(vector<edge>, vector<vector<int> >,vector<bool>, vector<bool>, int);// find cycles starting from v.
void isCyclicUtil(vector<edge>, vector<vector<int> >);// find all cycles.
bool dfs(vector<edge>, vector<vector<int> >, vector<bool>, int, int);//check if ‘‘to‘‘ is reachable from ‘‘from‘‘.
void isReachable(vector<edge>, vector<vector<int> >, int, int);
bool isBipartitie(vector<edge> , vector<vector<int> >,int v);//check if a graph is a bipartite graph.
int main(){
    int maxn = 5;
    vector<edge> edgelist;
    vector<vector<int> > G(maxn);

    buildMap(edgelist,G);

    //isCyclicUtil(edgelist, G);

    //isReachable(edgelist, G, 1, 1);

    if(isBipartitie(edgelist, G, 0)) cout<<"YES"<<endl;
    else cout<<"NO"<<endl;

    return 0;
}
bool isCyclic(vector<edge> edgelist, vector<vector<int> > G,vector<bool> vis, vector<bool> RecStack, int v){
    for(int i=0;i<G[v].size();++i){
        edge e = edgelist[G[v][i]];
        if(RecStack[e.to]) return true;
        if(!vis[e.to]){
            vis[e.to] = true; RecStack[e.to] = true;
            if(isCyclic(edgelist,G,vis,RecStack,e.to)) return true;
            RecStack[e.to] = false;
        }
    }
    return false;
}
void isCyclicUtil(vector<edge> edgelist, vector<vector<int> > G){// find all cycles.
    vector<bool> vis(G.size());
    vector<bool> RecStack(G.size());
    for(int i=0;i<vis.size();++i) vis[i]=false;
    for(int i=0;i<RecStack.size();++i) RecStack[i]=false;

    for(int i=0;i<G.size();++i){
        if(!vis[i]){
            vis[i] = true; RecStack[i] = true;
            if(isCyclic(edgelist,G,vis,RecStack,i)){
                cout<<i<<" starts a cycle"<<endl;
            }
            RecStack[i] = false;
        }
    }
}
void addEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){
    edgelist.push_back(edge(to));
    G[from].push_back(edgelist.size()-1);
}
void addDoubleEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){
    addEdge(edgelist,G,from,to);
    addEdge(edgelist,G,to,from);
}
bool dfs(vector<edge> edgelist, vector<vector<int> > G, vector<bool> vis, int from, int to){
    if(from == to) return true;
    for(int i=0;i<G[from].size();++i){
        edge e = edgelist[G[from][i]];
        if(e.to == to) return true;
        if(!vis[e.to]){
            vis[e.to] = true;
            if(dfs(edgelist, G, vis, e.to, to)) return true;
        }
    }
    return false;
}
void isReachable(vector<edge> edgelist, vector<vector<int> > G, int from, int to){
    vector<bool> vis(G.size());
    for(int i=0;i<vis.size();++i) vis[i] = false;
    vis[from] = true;
    if(dfs(edgelist, G, vis, from, to)) cout<<from<<" and "<<to<<" are reachable to each other"<<endl;
    else cout<<from<<" and "<<to<<" are not reachable to each other"<<endl;
}
bool isBipartitie(vector<edge> edgelist, vector<vector<int> > G,int v){
    vector<int> color(G.size());
    for(int i=0;i<color.size();++i) color[i] = -1;
    stack<int> st;
    while(!st.empty()) st.pop();

    st.push(v); color[v]=1;// 1 stands for RED, and 0 stands for BLUE, -1 stands for non-colored.

    while(!st.empty()){
        int k = st.top(); st.pop();

        for(int i=0;i<G[k].size();++i){
            edge e = edgelist[G[k][i]];
            if(color[e.to] == -1){
                color[e.to] = 1 - color[k];
                st.push(e.to);
            }
            else if(color[e.to] == color[k]) return false;
        }
    }
    return true;
}

时间: 2024-08-23 22:51:35

[email protected] Check whether a given graph is Bipartite or not的相关文章

Geeks - Check whether a given graph is Bipartite or not 二分图检查

检查一个图是否是二分图的算法 使用的是宽度搜索: 1 初始化一个颜色记录数组 2 利用queue宽度遍历图 3 从任意源点出发,染色0, 或1 4 遍历这点的邻接点,如果没有染色就染色与这个源点相反的颜色,如果已经染色并且和源点的值相反,那么就是合法点,如果是相同的颜色,那么就不能是二分图 参考:http://www.geeksforgeeks.org/bipartite-graph/ #include <stdio.h> #include <iostream> #include

[email&#160;protected]一个高效的配置管理工具--Ansible configure management--翻译(六)

无书面许可请勿转载 高级playbook Finding files with variables All modules can take variables as part of their arguments by dereferencing them with {{ and }} . You can use this to load a particular file based on a variable. For example, you might want to select a

【[email&#160;protected]基础篇 ~】# 磁盘与文件系统

之前三篇文章我们简单介绍了Linux系统的用户管理,文件操作等,都是比较浅显的基本操作.这节我们要深入一下了,从文件系统我们要看到磁盘系统.从磁盘系统我们要看到操作系统的整体架构.废话不多少让我们开始学习吧! 磁盘与文件系统 1.磁盘系统 1.1 磁盘结构 如图所示,磁盘由扇区和柱面组成,分区的最小单位是柱面(柱是有厚度的,本图是截面图),磁盘读取的最小单位是扇区.第一扇区的MBR(446bytes)分区表可以最大包含四个分区(64bytes)的信息,即从开始柱面到结束柱面4组数据,每组16个字

[email&#160;protected]:php

curl 获取页面信息 function curl_get_content($url){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) App

【PWN】[email&#160;protected]

#Exploit for [email protected] #@Windcarp 2015.07.05 from pwn import * #init context(arch = 'i386', os = 'linux') local=True if local: p = process("./urldecoder") libc = ELF("/lib/i386-linux-gnu/libc.so.6") else: p = remote("166.1

【EBS】adpatch报错:libgcc_s.so: undefined reference to `[email&#160;protected]_2.4&#39;

EBS通过adpatch打补丁报错 /usr/lib/gcc/x86_64-redhat-linux/4.4.7/32/libgcc_s.so: undefined reference to `[email protected]_2.4' collect2: ld returned 1 exit status make: *** [/soft/ebs12/ERPDB/apps/apps_st/appl/ad/12.0.0/bin/adwrknew] Error 1 Done with link 

[email&#160;protected]路由插件UI-Router

UI-Router是angular路由插件,上一篇我们讲到了angularJS自带路由,可惜在路径嵌套上表现的有所欠缺,而angular-UI-Router插件正好弥补了这一点. [示例]: □.UIRoute3.html:                     //先写总的路由文件 <!doctype html><html ng-app="routerApp"> <head>    <meta charset="utf-8&quo

[email&#160;protected]一个高效的配置管理工具--Ansible configure management--翻译(四)

无书面许可请勿转载 由于第三章内容较长,我将分做几个部分来翻译. Advanced Playbooks So far the playbooks that we have looked at are simple and just run a number of modules in order. Ansible allows much more control over the execution of your playbook. Using the following techniques

[email&#160;protected]一个高效的配置管理工具--Ansible configure management--翻译(十)

无书面许可,请勿转载 Custom Modules Until now we have been working solely with the tools provided to us by Ansible. This does afford us a lot of power, and make many things possible. However, if you have something particularly complex or if you find yourself u