|
| 1 | + |
| 2 | +class Solution { |
| 3 | +public: |
| 4 | + bool possibleBipartition(int N, vector<vector<int>>& dislikes) { |
| 5 | + vector<vector<int>> graph( N ); |
| 6 | + for ( auto x : dislikes ){ |
| 7 | + x[0]--;x[1]--; |
| 8 | + graph[x[0]].push_back(x[1]); |
| 9 | + graph[x[1]].push_back(x[0]); |
| 10 | + } |
| 11 | + queue< int > q; |
| 12 | + vector<int> color(N ,-1); |
| 13 | + for ( int v = 0; v < N ; v++){ |
| 14 | + if ( color[v] == -1){ |
| 15 | + q.push(v); |
| 16 | + color[v]=1; |
| 17 | + while( !q.empty()){ |
| 18 | + int top = q.front(); |
| 19 | + q.pop(); |
| 20 | + for ( int x : graph[top]){ |
| 21 | + if ( color[x] == -1){ |
| 22 | + color[x] = 3 - color[top]; |
| 23 | + q.push(x); |
| 24 | + } |
| 25 | + else if ( color[x] == color[top]) return false; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + return true; |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | +/* |
| 37 | +DFS |
| 38 | +*/ |
| 39 | + |
| 40 | + |
| 41 | +class Solution { |
| 42 | +public: |
| 43 | + |
| 44 | + int dfs( vector<vector<int>> graph , vector<int> &color , int src ,int col =1){ |
| 45 | + for ( int x : graph[src]){ |
| 46 | + if (color[x] == -1){ |
| 47 | + color[x] = 3 -col; |
| 48 | + if (!dfs(graph , color , x , 3 -col ,src)) return 0; |
| 49 | + } |
| 50 | + else if ( color[x] == col) return 0; |
| 51 | + } |
| 52 | + return 1; |
| 53 | + } |
| 54 | + |
| 55 | + |
| 56 | + bool possibleBipartition(int N, vector<vector<int>>& dislikes) { |
| 57 | + vector<vector<int>> graph( N ); |
| 58 | + for ( auto x : dislikes ){ |
| 59 | + x[0]--;x[1]--; |
| 60 | + graph[x[0]].push_back(x[1]); |
| 61 | + graph[x[1]].push_back(x[0]); |
| 62 | + } |
| 63 | + bool ok = true; |
| 64 | + vector<int> color(N ,-1); |
| 65 | + for ( int v = 0; v < N ; v++){ |
| 66 | + if ( color[v] == -1){ |
| 67 | + color[v] =1; |
| 68 | + ok&=dfs(graph ,color , v); |
| 69 | + } |
| 70 | + } |
| 71 | + return ok; |
| 72 | + } |
| 73 | +}; |
0 commit comments