Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create CheckBipartite.cpp #4

Merged
merged 1 commit into from
Oct 1, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions CPP/CheckBipartite.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//Check whether a graph is bipartite or not

#include<bits/stdc++.h>
#define max 10000 // Limit of vertices

int mat[max][max]; //Adjacency Matrix (to be taken as input)
int bfsQ[max]; //Queue for BFS
int r = -1;
int f = 0;
bool bfsVisited[max]; //Visited array for vertices
bool color[max]; //Color array for vertices

void makeBFS(int v, int n){ //make bfs and assign alternate colors to vertices
for(int i=0;i<n;i++){
if(mat[v][i] && !bfsVisited[i]){
bfsQ[++r] = i;
color[i] = !color[v];
}
}
if(f <= r){
bfsVisited[bfsQ[f]] = true;
makeBFS(bfsQ[f++], n);
}
}

bool checkBipartite(int n){ //check bipartite using 2-colored theorem
bool result = true;
int i;
for(i=0;i<max;i++){
bfsQ[i]=0;
bfsVisited[i]=false;
}
color[0] = true;
makeBFS(0,n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(mat[i][j] == 1 && color[i] == color[j]){
result = false;
break;
}
}
}
return result;
}

using namespace std;

int main(){
int n;
cout<<"Enter number of vertices : ";
cin>>n;
cout<<"Enter adjacency matrix: \n";
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>mat[i][j];
}
}
bool ch = checkBipartite(n);
cout<<boolalpha<<"\n Is the graph a Bipartite Graph? : \t"<<ch<<endl;
return 0;
}