LeetCode 题解工作台
不邻接植花
有 n 个花园,按从 1 到 n 标记。另有数组 paths ,其中 paths[i] = [x i , y i ] 描述了花园 x i 到花园 y i 的双向路径。在每个花园中,你打算种下四种花之一。 另外,所有花园 最多 有 3 条路径可以进入或离开. 你需要为每个花园选择一种花,使得通过路径相…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 图·DFS·traversal
答案摘要
我们先根据数组 构建图 ,其中 表示与花园 相邻的花园列表。 接下来,对于每个花园 ,我们先找出与 相邻的花园 ,并将 花园中种植的花的种类标记为已使用。然后我们从花的种类 开始枚举,直到找到一个未被使用的花的种类 ,将 标记为 花园中种植的花的种类,然后继续枚举下一个花园。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路
题目描述
有 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 <= 1040 <= paths.length <= 2 * 104paths[i].length == 21 <= xi, yi <= nxi != yi- 每个花园 最多 有 3 条路径可以进入或离开
解题思路
方法一:枚举
我们先根据数组 构建图 ,其中 表示与花园 相邻的花园列表。
接下来,对于每个花园 ,我们先找出与 相邻的花园 ,并将 花园中种植的花的种类标记为已使用。然后我们从花的种类 开始枚举,直到找到一个未被使用的花的种类 ,将 标记为 花园中种植的花的种类,然后继续枚举下一个花园。
枚举结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 和 分别是花园的数量和路径的数量。
class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
g = defaultdict(list)
for x, y in paths:
x, y = x - 1, y - 1
g[x].append(y)
g[y].append(x)
ans = [0] * n
for x in range(n):
used = {ans[y] for y in g[x]}
for c in range(1, 5):
if c not in used:
ans[x] = c
break
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for efficient use of graph traversal techniques, especially DFS.
- question_mark
Check for a proper implementation of the greedy coloring algorithm.
- question_mark
Ensure the solution correctly handles edge cases, such as minimal paths or no paths.
常见陷阱
外企场景- error
Incorrectly assuming there might be no valid flower assignments when there are always enough flower types available.
- error
Not implementing the graph traversal properly, leading to incorrect flower assignments or missed edges.
- error
Overcomplicating the problem with unnecessary data structures when a simple DFS-based greedy approach suffices.
进阶变体
外企场景- arrow_right_alt
Consider modifying the number of flower types to test how the algorithm scales with different constraints.
- arrow_right_alt
Explore whether a breadth-first search (BFS) approach could provide advantages in some cases over DFS.
- arrow_right_alt
Test the algorithm’s performance on large graphs with up to 10^4 gardens and 2 * 10^4 paths.