-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPossible Bipartition(DFS).cpp
47 lines (41 loc) · 1.27 KB
/
Possible Bipartition(DFS).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
private:
bool dfs(vector<vector<int>>& graph, vector<int>& group, int node, int color) {
if (group[node] != 0) {
if (group[node] != color) {
return false;
}
return true;
}
group[node] = color;
for (auto& neighbor : graph[node]) {
int nextColor;
if (color == 1) {
nextColor = 2;
} else {
nextColor = 1;
}
if (dfs(graph, group, neighbor, nextColor) == false) {
return false;
}
}
return true;
}
public:
bool possibleBipartition(int n, vector<vector<int>>& dislikes) {
vector<vector<int>> graph(n + 1);
vector<int> group(n + 1, 0); // 0 indicates unvisited, 1 and 2 are the two groups
for (int i = 0; i < dislikes.size(); i++) {
graph[dislikes[i][0]].push_back(dislikes[i][1]);
graph[dislikes[i][1]].push_back(dislikes[i][0]);
}
for (int i = 1; i <= n; i++) {
if (group[i] == 0) {
if (dfs(graph, group, i, 1) == false) { // Start DFS with color 1
return false;
}
}
}
return true;
}
};