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 <= N <= 10000
0 <= paths.size <= 20000
- No garden has 4 or more paths coming into or leaving it.
- It is guaranteed an answer exists.
Solution: Graph coloring, choose any available color
Time complexity: O(|V|+|E|)
Space complexity: O(|V|+|E|)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Solution { public: vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) { vector<int> ans(N, 0); vector<vector<int>> G(N); for (const auto& 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 mask = 0; for (const auto& j : G[i]) mask |= (1 << ans[j]); for (int c = 1; c <= 4 && ans[i] == 0; ++c) if (!(mask & (1 << c))) ans[i] = c; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment