题目描述
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]
算法1
(贪心) $O(n^2)$
建立无向图的连接,遍历每一个节点,用color数组标记该节点的邻节点j颜色res[j]为已分配,然后在四种颜色中找到一个未分配的颜色给i节点,if color[c]==0, res[i]=c
时间复杂度
参考文献
C++ 代码
class Solution {
public:
vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
vector<int> res(N);
vector<vector<int>> G(N);
for (vector<int>& p : paths) {
G[p[0] - 1].push_back(p[1] - 1);
G[p[1] - 1].push_back(p[0] - 1);
}
for (int i = 0; i < N; ++i) {
int colors[5] = {};
for (int j : G[i]) //mark neighbour as used
colors[res[j]] = 1;
for (int c = 1; c <= 4; ++c)
{
if (!colors[c]) //assign a unused color to i node
{
res[i] = c;
break;
}
}
}
return res;
}
};