C++ Program to Check whether Graph is a 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. }

advertisement
$ 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
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn