forked from sauravgpt2/hacktoberfest36_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBipartite_Graph.cpp
59 lines (47 loc) · 1.09 KB
/
Bipartite_Graph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
bool dfs_helper(vector<int> graph[], int node, int parent, int *visited, int color) {
//if color equals 1 or 2, it means it is visited
visited[node] = color;
for(auto nbr : graph[node]) {
if(visited[nbr] == 0) {
//check for neighbour of current node
bool subprob = dfs_helper(graph, nbr, node, visited, 3-color);
if(!subprob) {
return false;
}
}
//Cycle detected
else if(nbr!=parent && visited[nbr] == color) {
return false;
}
}
return true;
}
bool dfs(vector<int> graph[], int N) {
//Initially all nodes are marked 0 (not visited)
int visited[N] = {0};
bool ans = dfs_helper(graph, 1, -1, visited, 1);
return ans;
}
int main() {
int N,x,y,e;
cout<<"Enter the number of nodes: ";
cin>>N;
cout<<"Enter the number of edges: ";
cin>>e;
N++;
vector<int> graph[N];
cout<<"Enter the nodes present at each edge\n";
for(int i=0;i<e;i++) {
cin>>x>>y;
graph[x].push_back(y);
graph[y].push_back(x);
}
if(dfs(graph, N)) {
cout<<"Bipartite Graph\n";
}else {
cout<<"Non Bipartite Graph\n";
}
return 0;
}