Iam_Sandeep

bipartite graph

Jun 5th, 2021 (edited)
910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. // { Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  // } Driver Code Ends
  6. /*
  7. algorithm:bfs
  8. method: check whether vertex coloring==2?
  9. -1------------------------->not visited
  10. 0 -------------------------> color 1
  11. 1-------------------------->color 2
  12. */
  13.  
  14.  
  15.  
  16. class Solution {
  17. public:
  18. bool bfs(vector<int> adj[],int colors[],int src){
  19.         queue<int> q;
  20.         q.push(src);
  21.         colors[src]=0;
  22.         while(!q.empty()){
  23.             int t=q.front();
  24.             q.pop();
  25.             for(auto i:adj[t])
  26.                 if (i==t)
  27.                     return false;
  28.                 else if (colors[i]==-1 ){
  29.                 colors[i]=1-colors[t];
  30.                 q.push(i);
  31.                        }
  32.                 else if (colors[i]==colors[t])
  33.                 return false;
  34.                 }
  35.         return true;
  36.        
  37. }
  38.     bool isBipartite(int V, vector<int>adj[]){
  39.         // Code here
  40.         int colors[V];
  41.        // memset(colors,-1,sizeof(colors));
  42.        for(int i=0;i<V;++i)
  43.         colors[i]=-1;
  44.         for(int i=0;i<V;++i)
  45.         if (colors[i]==-1 && !bfs(adj,colors,i))
  46.             return false;
  47.        return true;
  48.            
  49.        
  50.     }
  51.  
  52. };
  53.  
  54. // { Driver Code Starts.
  55. int main(){
  56.     int tc;
  57.     cin >> tc;
  58.     while(tc--){
  59.         int V, E;
  60.         cin >> V >> E;
  61.         vector<int>adj[V];
  62.         for(int i = 0; i < E; i++){
  63.             int u, v;
  64.             cin >> u >> v;
  65.             adj[u].push_back(v);
  66.             adj[v].push_back(u);
  67.         }
  68.         Solution obj;
  69.         bool ans = obj.isBipartite(V, adj);    
  70.         if(ans)cout << "1\n";
  71.         else cout << "0\n";  
  72.     }
  73.     return 0;
  74. }  // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment