C++ Program to Check whether a Graph is Bipartite using BFS

This C++ Program checks whether Graph is a Bipartite using BFS

Here is source code of the C++ Program to check whether Graph is a Bipartite using BFS. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Check whether Graph is a Bipartite using BFS
  3.  */
  4. #include <iostream>
  5. #include <queue>
  6. #define V 4
  7. using namespace std;
  8.  
  9. /* 
  10.  * Returns true if graph G[V][V] is Bipartite
  11.  */
  12. bool isBipartite(int G[][V], int src)
  13. {
  14.     int colorArr[V];
  15.     for (int i = 0; i < V; ++i)
  16.         colorArr[i] = -1;
  17.     colorArr[src] = 1;
  18.     queue <int> q;
  19.     q.push(src);
  20.     while (!q.empty())
  21.     {
  22.         int u = q.front();
  23.         q.pop();
  24. 	for (int v = 0; v < V; ++v)
  25.         {
  26.             if (G[u][v] && colorArr[v] == -1)
  27.             {
  28.                 colorArr[v] = 1 - colorArr[u];
  29.                 q.push(v);
  30.             }
  31.             else if (G[u][v] && colorArr[v] == colorArr[u])
  32.                 return false;
  33.         }
  34.     }
  35.     return true;
  36. }
  37.  
  38. /* 
  39.  * Main Contains Menu 
  40.  */
  41. int main()
  42. {
  43.     int G[][V] = {{0, 1, 0, 1},
  44.         {1, 0, 1, 0},
  45.         {0, 1, 0, 1},
  46.         {1, 0, 1, 0}
  47.     };
  48.     if (isBipartite(G, 0)) 
  49.         cout << "The Graph is Bipartite"<<endl;
  50.     else
  51.         cout << "The Graph is Not Bipartite"<<endl;
  52.     return 0;
  53. }

$ g++ bipartite_bfs.cpp
$ a.out
The Graph is Bipartite
 
 
------------------
(program exited with code: 1)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.