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 5 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
47 changes: 47 additions & 0 deletions code/graph_algorithms/src/Bipartite_check/bipartite.cpp
@@ -0,0 +1,47 @@
#include <iostream>
#include <vector>
#include <queue>
int main()
{
long int vertex , edge , u , v , c ;
bool flag=false;
Copy link
Member

Choose a reason for hiding this comment

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

Could you format your code please. Please follow our C++ style guide, located in guides/coding_style/C++/README.md I believe.

// taking n ->number of vertex and m -> number of edges
std::cin >> vertex >> edge;
// 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)
{
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=true;
}
}
}
if( !flag )
std::cout << "Graph is bipartite" << "\n" ;
else
std::cout << "Graph is not bipartite" << "\n" ;
}