We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.
Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return trueif it is possible to split everyone into two groups in this way.
The key idea is to check if the graph is bipartite: can we color the graph with two colors such that no two adjacent nodes have the same color? If yes, a bipartition is possible. This can be done using DFS coloring or Union-Find by grouping each node with the opposite group of its neighbors.
classSolution {
publicbooleanpossibleBipartition(int n, int[][] dislikes) {
List<Integer>[] g =new List[n];
for (int i = 0; i < n; i++) g[i]=new ArrayList<>();
for (int[] e : dislikes) {
g[e[0]-1].add(e[1]-1);
g[e[1]-1].add(e[0]-1);
}
int[] color =newint[n];
Arrays.fill(color, -1);
for (int i = 0; i < n; i++) {
if (color[i]==-1 &&!dfs(i, 0, color, g)) returnfalse;
}
returntrue;
}
privatebooleandfs(int u, int c, int[] color, List<Integer>[] g) {
color[u]= c;
for (int v : g[u]) {
if (color[v]==-1) {
if (!dfs(v, 1-c, color, g)) returnfalse;
} elseif (color[v]== c) {
returnfalse;
}
}
returntrue;
}
}
classSolution {
funpossibleBipartition(n: Int, dislikes: Array<IntArray>): Boolean {
val g = Array(n) { mutableListOf<Int>() }
for (e in dislikes) {
g[e[0]-1].add(e[1]-1)
g[e[1]-1].add(e[0]-1)
}
val color = IntArray(n) { -1 }
fundfs(u: Int, c: Int): Boolean {
color[u] = c
for (v in g[u]) {
if (color[v] == -1) {
if (!dfs(v, 1-c)) returnfalse } elseif (color[v] == c) {
returnfalse }
}
returntrue }
for (i in0 until n) if (color[i] == -1&& !dfs(i, 0)) returnfalsereturntrue }
}
classSolution:
defpossibleBipartition(self, n: int, dislikes: list[list[int]]) -> bool:
g = [[] for _ in range(n)]
for u, v in dislikes:
g[u-1].append(v-1)
g[v-1].append(u-1)
color = [-1] * n
defdfs(u: int, c: int) -> bool:
color[u] = c
for v in g[u]:
if color[v] ==-1:
ifnot dfs(v, 1-c):
returnFalseelif color[v] == c:
returnFalsereturnTruefor i in range(n):
if color[i] ==-1andnot dfs(i, 0):
returnFalsereturnTrue