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 true if it is possible to split everyone into two groups in this way.
Example 1: Input: n = 4, dislikes = [[1,2],[1,3],[2,4]] Output: true Explanation: The first group has [1,4], and the second group has [2,3].
Example 2: Input: n = 3, dislikes = [[1,2],[1,3],[2,3]] Output: false Explanation: We need at least 3 groups to divide them. We cannot put them in two groups.
Constraints: 1 <= n <= 2000 0 <= dislikes.length <= 104 dislikes[i].length == 2 1 <= ai < bi <= n All the pairs of dislikes are unique.
可能的二分法。
给定一组 n 人(编号为 1, 2, ..., n), 我们想把每个人分进任意大小的两组。每个人都可能不喜欢其他人,那么他们不应该属于同一组。
给定整数 n 和数组 dislikes ,其中 dislikes[i] = [ai, bi] ,表示不允许将编号为 ai 和 bi的人归入同一组。当可以用这种方法将所有人分进两组时,返回 true;否则返回 false。
classSolution { publicbooleanpossibleBipartition(int n, int[][] dislikes) { List<List<Integer>> g = newArrayList<>(); for (inti=0; i <= n; i++) { g.add(newArrayList<>()); }
for (int[] d : dislikes) { g.get(d[0]).add(d[1]); g.get(d[1]).add(d[0]); }
int[] colors = newint[n + 1]; for (inti=0; i <= n; i++) { if (colors[i] != 0) { continue; } Queue<Integer> queue = newLinkedList<>(); queue.offer(i); colors[i] = 1; while (!queue.isEmpty()) { intcur= queue.poll(); for (int nei : g.get(cur)) { if (colors[nei] == 0) { colors[nei] = -colors[cur]; queue.offer(nei); } elseif (colors[nei] == colors[cur]) { returnfalse; } } } } returntrue; } }