Advertisement
knakul853

Untitled

Jul 24th, 2020
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool isBipartite(vector<vector<int>>& graph) {
  4.        
  5.         int n = (int)graph.size();
  6.        
  7.         vector<vector<int>>g(n);
  8.        
  9.         for(int i=0;i<n;i++){
  10.             auto temp = graph[i];
  11.            
  12.             for(int j:temp){
  13.                 g[i].push_back(j);
  14.                 g[j].push_back(i);
  15.             }
  16.         }
  17.        
  18.         vector<int>col(n, -1);
  19.         for(int i=0;i<n;i++){
  20.             if(col[i] == -1){
  21.                 if(!dfs(i, 0, g, col)) return false;
  22.             }
  23.         }
  24.        
  25.         return true;
  26.     }
  27.    
  28.    
  29.     bool dfs(int node, int c, vector<vector<int>>&g, vector<int>&col){
  30.        
  31.         col[node]=c;
  32.        
  33.         bool res = true;
  34.         for(int child:g[node]){
  35.             if(col[child] == -1){
  36.                 res&=dfs(child, 1-c, g, col);
  37.             }
  38.             if(col[child] == c){
  39.                 return false;
  40.             }
  41.         }
  42.        
  43.         return res;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement