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

program to check undirected graph is bipartite or not in c++ #3958

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 46 additions & 0 deletions code/graph_algorithms/src/Bipartite_check/bipartite.cpp
@@ -0,0 +1,46 @@
#include<iostream>
#include<vector>
#include<queue>
quantum08 marked this conversation as resolved.
Show resolved Hide resolved
int main()
{
long int vertex,edge,u,v,c,flag=0;
quantum08 marked this conversation as resolved.
Show resolved Hide resolved
// taking n ->number of vertex and m -> number of edges
std::cin>>vertex>>edge;
quantum08 marked this conversation as resolved.
Show resolved Hide resolved
// adj is 2-D vector to store edges between vertex
std::vector<std::vector<long int > >adj(vertex,std::vector<long int>());
// color is use to store color of vertex
std::vector<long int> color(vertex,-1);
std::queue<long int>q;
//for number of edges times
for(int i=0;i<edge;i++)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use pre-increment.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also use pre-increment operator now

{
std::cin>>u>>v;
adj[u-1].push_back(v-1);
adj[v-1].push_back(u-1);
}
u=0;
color[u]=0;
q.push(u);
while(!q.empty())
{
c=q.front();
q.pop();
for(auto i=adj[c].begin();i!=adj[c].end();i++)
{
// updating color of vertex
if(color[*i]==-1 )
{
q.push(*i);
color[*i]=1-color[c];
}
else if(color[*i]==color[c]) // checking for bipartite graph
{
flag=1;
}
}
}
if(flag==0)
std::cout<<"Graph is bipartite";
else
std::cout<<"Graph is not bipartite";
}