Advertisement
kartikkukreja

Testing Bipartiteness

Aug 23rd, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5.  
  6. enum Color {Uncolored, Red, Black};
  7.  
  8. // Adjacency list representation for graph
  9. // Assumes vertices are labeled 0...V-1, where V is the number of vertices
  10. class Graph {
  11. public:
  12.     vector <int> * adjList;
  13.     int V;
  14.     Graph(int V)    {
  15.         adjList = new vector <int>[V];
  16.         this->V = V;
  17.     }
  18.     void addUndirectedEdge(int u, int v)    {
  19.         adjList[u].push_back(v);
  20.         adjList[v].push_back(u);
  21.     }
  22. };
  23.  
  24. // checks if graph G is bipartite. G is assumed to be connected
  25. bool isBipartite(Graph& G, int s)  {
  26.     Color * coloring = new Color[G.V];
  27.     for (int i = 0; i < G.V; i++)
  28.         coloring[i] = Uncolored;
  29.     coloring[s] = Red;
  30.  
  31.     queue <int> q;
  32.     q.push(s);
  33.  
  34.     while (!q.empty())  {
  35.         int u = q.front();
  36.         q.pop();
  37.         for (vector <int>::iterator it = G.adjList[u].begin(); it != G.adjList[u].end(); it++)  {
  38.             if (coloring[*it] == Uncolored) {
  39.                 coloring[*it] = (coloring[u] == Red) ? Black : Red;
  40.                 q.push(*it);
  41.             } else if (coloring[*it] == coloring[u])    {
  42.                 delete [] coloring;
  43.                 return false;
  44.             }
  45.         }
  46.     }
  47.     delete [] coloring;
  48.     return true;
  49. }
  50.  
  51. int main()  {
  52.     Graph G(5);
  53.  
  54.     G.addUndirectedEdge(0, 2);
  55.     G.addUndirectedEdge(0, 3);
  56.     G.addUndirectedEdge(0, 4);
  57.     G.addUndirectedEdge(1, 2);
  58.     G.addUndirectedEdge(1, 3);
  59.     G.addUndirectedEdge(4, 3);
  60.  
  61.     if (isBipartite(G, 0))
  62.         printf("Bipartite");
  63.     else
  64.         printf("Not bipartite");
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement