1042. Flower Planting With No Adjacent
Description
You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.
All gardens have at most 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] Explanation: Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].
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]
Constraints:
1 <= n <= 1040 <= paths.length <= 2 * 104paths[i].length == 21 <= xi, yi <= nxi != yi- Every garden has at most 3 paths coming into or leaving it.
Solutions
Solution 1: Enumeration
Thinking
Degree is at most three and there are four colors, so a greedy coloring works and backtracking is unnecessary.
Build the adjacency list. For garden \(x\) collect colors already used by neighbors and assign the first free color in \(1..4\).
A vertex of degree \(\le 3\) always has a free color; one pass finishes.
We first construct a graph \(g\) based on the array \(\textit{paths}\), where \(g[x]\) represents the list of gardens adjacent to garden \(x\).
Next, for each garden \(x\), we first find the gardens \(y\) adjacent to \(x\) and mark the types of flowers planted in garden \(y\) as used. Then, we enumerate the flower types starting from \(1\) until we find a flower type \(c\) that has not been used. We assign \(c\) as the flower type for garden \(x\) and continue to the next garden.
After the enumeration is complete, we return the result.
The time complexity is \(O(n + m)\), and the space complexity is \(O(n + m)\), where \(n\) is the number of gardens and \(m\) is the number of paths.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |