Possible Bipartition
Input:
N =
4
, dislikes =
[[1,2],[1,3],[2,4]]
Output:
true
Explanation
: group1 [1,4], group2 [2,3]Input:
N =
3
, dislikes =
[[1,2],[1,3],[2,3]]
Output:
falseThoughts
Code
Analysis
Last updated
Input:
N =
4
, dislikes =
[[1,2],[1,3],[2,4]]
Output:
true
Explanation
: group1 [1,4], group2 [2,3]Input:
N =
3
, dislikes =
[[1,2],[1,3],[2,3]]
Output:
falseLast updated
class Solution {
public boolean possibleBipartition(int N, int[][] dislikes) {
Map<Integer, Integer> color = new HashMap<>();
List<Integer>[] graph = new ArrayList[N + 1];
for (int i = 1; i <= N; i++) {
graph[i] = new ArrayList<>();
}
for (int[] edge : dislikes) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
for (int i = 1; i <= N; i++) {
if (!color.containsKey(i) && !dfs(i, 0, color, graph)) {
return false;
}
}
return true;
}
private boolean dfs(int i, int c, Map<Integer, Integer> color, List<Integer>[] graph) {
if (color.containsKey(i)) {
if (color.get(i) != c) {
return false;
}
return true;
}
color.put(i, c);
for (int nei : graph[i]) {
if (!dfs(nei, c ^ 1, color, graph)) {
return false;
}
}
return true;
}
}