-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPossibleBipartition.java
More file actions
41 lines (32 loc) · 1.02 KB
/
Copy pathPossibleBipartition.java
File metadata and controls
41 lines (32 loc) · 1.02 KB
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
class Solution {
public boolean possibleBipartition(int n, int[][] dislikes) {
HashMap<Integer, List<Integer>> adj = new HashMap<>();
for (int i = 0; i < n; i++) {
adj.put(i, new ArrayList<Integer>());
}
for (int i = 0; i < dislikes.length; i++) {
adj.get(dislikes[i][0] - 1).add(dislikes[i][1] - 1);
adj.get(dislikes[i][1] - 1).add(dislikes[i][0] - 1);
}
int[] groups = new int[n];
for (int i = 0; i < n; i++) {
if (groups[i] == 0 && !dfs(i, adj, groups, 1)) {
return false;
}
}
return true;
}
private boolean dfs(int node, HashMap<Integer, List<Integer>> adj, int[] groups, int group) {
groups[node] = group;
for (int i = 0; i < adj.get(node).size(); i++) {
int neighbor = adj.get(node).get(i);
if (groups[neighbor] == group) {
return false;
}
if (groups[neighbor] == 0 && !dfs(neighbor, adj, groups, -group)) {
return false;
}
}
return true;
}
}