bipartite graph dfs

Solutions on MaxInterview for bipartite graph dfs by the best coders in the world

showing results for - "bipartite graph dfs"
Sofia
25 Aug 2017
1//Bipartite graph / Graph coloring
2//Using DFS(recursion)
3
4#include<bits/stdc++.h>
5using namespace std;
6void addedge(vector<int>adj[],int u,int v)
7{
8    adj[u].push_back(v);
9    adj[v].push_back(u);
10}
11bool bipar(int sr,vector<int>adj[],int color[])
12{
13    if(color[sr]==-1)
14    {
15        color[sr]=1;
16    }
17    for(auto i:adj[sr])
18    {
19        if(color[i]==-1)
20        {
21            color[i]=1-color[sr];
22            if(!bipar(i,adj,color))
23            {
24                return false;
25            }
26        }
27        else if(color[i]==color[sr])
28        {
29            return false;
30        }
31    }
32    return true;
33}
34bool checkbipar(vector<int>adj[],int n)
35{
36    int color[n];
37    for(int i=0;i<n;i++)
38    {
39        color[i]=-1;
40    }
41    for(int i=0;i<n;i++)
42    {
43        if(color[i]==-1)
44        {
45            if(!bipar(i,adj,color))
46            {
47                return false;
48            }
49        }
50    }
51    return true;
52}
53int main()
54{
55    int n,v;
56    cout<<"Enter the no. of vertex and edges:";
57    cin>>n>>v;
58    vector<int>adj[n];
59    int a,b;
60    cout<<"enter the links:"<<endl;
61    for(int i=0;i<n;i++)
62    {
63        cin>>a>>b;
64        addedge(adj,a,b);
65    }
66    if(checkbipar(adj,n))
67    {
68        cout<<"YES"<<endl;
69    }
70    else
71    {
72        cout<<"NO"<<endl;
73    }
74}
75
similar questions
queries leading to this page
bipartite graph dfs