File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
May-LeetCoding-Challenge/27-Possible-Bipartition Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ vector<int > color;
4
+ vector<vector<int >> G;
5
+
6
+ bool bipartite (int u) {
7
+ for (int i = 0 ; i < G[u].size (); i++) {
8
+ int v = G[u][i];
9
+ if (color[v] == color[u]) return false ;
10
+ if (!color[v]) {
11
+ color[v] = 3 - color[u];
12
+ if (!bipartite (v)) return false ;
13
+ }
14
+ }
15
+ return true ;
16
+ }
17
+
18
+ bool possibleBipartition (int N, vector<vector<int >>& dislikes) {
19
+ color.resize (N+1 );
20
+ G.resize (N+1 );
21
+
22
+
23
+ for (int i = 0 ; i < dislikes.size (); i++) {
24
+ G[dislikes[i][0 ]].push_back (dislikes[i][1 ]);
25
+ G[dislikes[i][1 ]].push_back (dislikes[i][0 ]);
26
+ }
27
+
28
+ for (int i = 1 ; i <= N; i++)
29
+ if (!color[i]){
30
+ color[i] = 1 ;
31
+ if (!bipartite (i)) return false ;
32
+ }
33
+ return true ;
34
+
35
+ }
36
+ };
You can’t perform that action at this time.
0 commit comments