> 文章列表 > LeetCode 1042. 不邻接植花

LeetCode 1042. 不邻接植花

LeetCode 1042. 不邻接植花

【LetMeFly】1042.不邻接植花

力扣题目链接:https://leetcode.cn/problems/flower-planting-with-no-adjacent/

n花园,按从 1 到 n 标记。另有数组 paths ,其中 paths[i] = [xi, yi] 描述了花园 xi 到花园 yi 的双向路径。在每个花园中,你打算种下四种花之一。

另外,所有花园 最多3 条路径可以进入或离开.

你需要为每个花园选择一种花,使得通过路径相连的任何两个花园中的花的种类互不相同。

以数组形式返回 任一 可行的方案作为答案 answer,其中 answer[i] 为在第 (i+1) 个花园中种植的花的种类。花的种类用  1、2、3、4 表示。保证存在答案。

 

示例 1:

输入:n = 3, paths = [[1,2],[2,3],[3,1]]
输出:[1,2,3]
解释:
花园 1 和 2 花的种类不同。
花园 2 和 3 花的种类不同。
花园 3 和 1 花的种类不同。
因此,[1,2,3] 是一个满足题意的答案。其他满足题意的答案有 [1,2,4]、[1,4,2] 和 [3,2,1]

示例 2:

输入:n = 4, paths = [[1,2],[3,4]]
输出:[1,2,1,2]

示例 3:

输入:n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
输出:[1,2,3,4]

 

提示:

  • 1 <= n <= 104
  • 0 <= paths.length <= 2 * 104
  • paths[i].length == 2
  • 1 <= xi, yi <= n
  • xi != yi
  • 每个花园 最多3 条路径可以进入或离开

方法一:图染色

首先需要明确的是,每个花园最多相邻三个另外的花园,而且有4种颜色的花可以种植,因此根本不需要考虑染色的顺序等问题,其他花园随便染,到我至少还剩一种颜色可以染。

所以这就好办了,首先将给定的路径建图,使得graph[i] = {a1, a2, …}代表点i相邻的点为a1,a2,…

接下来使用答案数组ans,其中ans[i]代表第i个花园的花朵的颜色。

这样,我们只需要从0到n - 1遍历花园,对于某个花园i,我们统计出所有的与之相邻的花园的颜色,将这个花园的颜色赋值为周围花园未出现过的颜色即可。

  • 时间复杂度O(n)O(n)O(n)
  • 空间复杂度O(len(paths)+n)O(len(paths) + n)O(len(paths)+n)

AC代码

C++

class Solution {
public:vector<int> gardenNoAdj(int n, vector<vector<int>>& paths) {vector<int> ans(n);vector<vector<int>> graph(n);for (vector<int>& path : paths) {graph[path[0] - 1].push_back(path[1] - 1);graph[path[1] - 1].push_back(path[0] - 1);}for (int i = 0; i < n; i++) {bool already[5] = {false, false, false, false, false};for (int toPoint : graph[i]) {already[ans[toPoint]] = true;}for (int j = 1; j < 5; j++) {if (!already[j]) {ans[i] = j;break;}}}return ans;}
};

Python

# from typing import Listclass Solution:def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:ans = [0] * ngraph = [[] for _ in range(n)]for path in paths:graph[path[0] - 1].append(path[1] - 1)graph[path[1] - 1].append(path[0] - 1)for i in range(n):visited = [False] * 5for toPoint in graph[i]:visited[ans[toPoint]] = Truefor j in range(1, 5):if not visited[j]:ans[i] = jbreakreturn ans

同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/130168403