[LeetCode] 1042. Flower Planting With No Adjacent
You have n
gardens, labeled from 1
to n
, and an array paths
where paths[i] = [xi, yi]
describes a bidirectional path between garden xi
to garden yi
. In each garden, you want to plant one of 4 types of flowers.
All gardens have at most 3 paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return any such a choice as an array answer
, where answer[i]
is the type of flower planted in the (i+1)th
garden. The flower types are denoted 1
, 2
, 3
, or 4
. It is guaranteed an answer exists.
Example 1:
Input: n = 3, paths = [[1,2],[2,3],[3,1]] Output: [1,2,3] Explanation: Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].
Example 2:
Input: n = 4, paths = [[1,2],[3,4]] Output: [1,2,1,2]
Example 3:
Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] Output: [1,2,3,4]
Constraints:
1 <= n <= 104
0 <= paths.length <= 2 * 104
paths[i].length == 2
1 <= xi, yi <= n
xi != yi
- Every garden has at most 3 paths coming into or leaving it.
不邻接植花。
有 n 个花园,按从 1 到 n 标记。另有数组 paths ,其中 paths[i] = [xi, yi] 描述了花园 xi 到花园 yi 的双向路径。在每个花园中,你打算种下四种花之一。
另外,所有花园 最多 有 3 条路径可以进入或离开.
你需要为每个花园选择一种花,使得通过路径相连的任何两个花园中的花的种类互不相同。
以数组形式返回 任一 可行的方案作为答案 answer,其中 answer[i] 为在第 (i+1) 个花园中种植的花的种类。花的种类用 1、2、3、4 表示。保证存在答案。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/flower-planting-with-no-adjacent
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 DFS + 染色。题目说每个花园你都要种花,那么意味着你需要遍历整个图。这里我用 hashmap 把图建立起来,之后开始遍历,遍历的时候我还用了一个长度为 5 的 boolean 数组记录每个 node 的邻居节点是否有被染色过。长度为什么是 5 是因为题目说可以用1 - 4来染色,为了处理 0 方便我就把长度定为 5。注意题目给的 path 里面的数字在建图的时候需要 - 1。其余部分参见代码注释。
时间O(V + E)
空间O(n)
Java实现
1 class Solution { 2 public int[] gardenNoAdj(int n, int[][] paths) { 3 // 建图 4 HashMap<Integer, Set<Integer>> g = new HashMap<>(); 5 for (int i = 0; i < n; i++) { 6 g.put(i, new HashSet<>()); 7 } 8 for (int[] p : paths) { 9 int from = p[0] - 1; 10 int to = p[1] - 1; 11 g.get(from).add(to); 12 g.get(to).add(from); 13 } 14 15 // 记录每个位置填什么颜色 16 int[] res = new int[n]; 17 for (int i = 0; i < n; i++) { 18 // 如果邻居节点有上过色的,标记一下 19 boolean[] used = new boolean[5]; 20 for (int j : g.get(i)) { 21 used[res[j]] = true; 22 } 23 for (int c = 1; c <= 4; c++) { 24 // 给当前位置上色 25 if (used[c] == false) { 26 res[i] = c; 27 } 28 } 29 } 30 return res; 31 } 32 }