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 all 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 , counter ;
bool flag = false;
// 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())
{
counter=q.front();
q.pop();
for (auto i=adj[counter].begin();i!=adj[counter].end(); ++i)
{
// updating color of vertex
if (color[*i]==-1)
{
q.push(*i);
color[*i]=1-color[counter];
}
else if (color[*i]==color[counter])
{
flag=true;
}
}
}
if ( !flag )
std::cout << "Graph is bipartite" << "\n" ;
else
std::cout << "Graph is not bipartite" << "\n" ;
}