Skip to content

Commit 2a3cf47

Browse files
committed
886. Possible Bipartition
1 parent d5e1e21 commit 2a3cf47

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

possible-bipartition.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Runtime: 432 ms
2+
// Memory Usage: 72.5 MB
3+
class Solution {
4+
public:
5+
6+
bool solve(vector<vector<int> > &adj, vector<bool> &vis, vector<int> &group, int src) {
7+
bool res = true;
8+
int nextGrp = (group[src] + 1) % 2;
9+
for (int a : adj[src]) {
10+
if (vis[a] && group[a] == group[src]) {
11+
return false;
12+
}
13+
if (!vis[a]) {
14+
group[a] = nextGrp;
15+
vis[a] = true;
16+
if (!solve(adj, vis, group, a)) {
17+
return false;
18+
}
19+
}
20+
}
21+
return true;
22+
}
23+
24+
bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
25+
vector<vector<int> > adj(N + 1);
26+
for (auto a : dislikes) {
27+
adj[a[0]].push_back(a[1]);
28+
adj[a[1]].push_back(a[0]);
29+
}
30+
vector<bool> vis(N + 1, 0);
31+
vector<int> group(N + 1, -1);
32+
for (int i = 1; i <= N; i++) {
33+
if (!vis[i]) {
34+
group[i] = 0;
35+
if (!solve(adj, vis, group, i)) {
36+
return false;
37+
}
38+
}
39+
}
40+
return true;
41+
}
42+
};

0 commit comments

Comments
 (0)