Skip to content

Commit c3a2dd8

Browse files
committed
add cpp solution
1 parent db1d98c commit c3a2dd8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
};

0 commit comments

Comments
 (0)