1042. Flower Planting With No Adjacent 不邻接植花

@TOC

# 题目描述

You have `N` gardens, labelled `1` to `N`. In each garden, you want to plant one of 4 types of flowers.

`paths[i] = [x, y]` describes the existence of a bidirectional path from garden `x` to garden `y`.

Also, there is no garden that has more than 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]
``````

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]
``````

Note:

1. `1 <= N <= 10000`
2. `0 <= paths.size <= 20000`
3. No garden has 4 or more paths coming into or leaving it.
4. It is guaranteed an answer exists.

# 题目大意

N表示顶点数，paths表示这两个顶点（编号从1开始）之间有边。

# 解题方法

# 图

Python代码如下：

``````class Solution(object):
"""
:type N: int
:type paths: List[List[int]]
:rtype: List[int]
"""
res = [0] * N
graph = [[] for i 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):
neighbor_colors = []
for neighbor in graph[i]:
neighbor_colors.append(res[neighbor])
for color in range(1, 5):
if color in neighbor_colors:
continue
res[i] = color
break
return res
``````

C++代码如下：

``````class Solution {
public:
vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
vector<int> res(N, 0);
vector<vector<int>> graph(N);
for (auto& 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) {
unordered_set<int> neighbor_colors;
for (int neighbor : graph[i]) {
neighbor_colors.insert(res[neighbor]);
}
for (int color = 1; color < 5; ++color) {
if (neighbor_colors.count(color))
continue;
res[i] = color;
break;
}
}
return res;
}
};
``````

# 日期

2019 年 6 月 9 日 —— 简单的题没有难度，需要挑战有难度的才行