Flower Planting With No Adjacent Problem
Description
LeetCode Problem 1042.
You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [x_i, y_i] describes a bidirectional path between garden x_i to garden y_i. 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 <= 10^40 <= paths.length <= 2 * 10^4paths[i].length == 21 <= x_i, y_i <= nx_i != y_i- Every garden has at most 3 paths coming into or leaving it.
Solution
Approach: Greedy Coloring
Every garden has at most 3 neighbours, and there are 4 flower types. However the neighbours are planted, they use at most 3 types, so at least one type is always free for the current garden.
That makes a simple greedy pass work, with no backtracking:
- Build an adjacency list from
paths. - Go through the gardens in order. For garden
x, collect the types already given to its neighbours (unplanted neighbours have type0, which blocks nothing). - Give
xthe smallest type from 1 to 4 that is not in that set.
A later garden never forces an earlier one to change, because when the later one is planted it simply avoids the earlier choices.
Any valid answer is accepted, so the judge checks that every garden gets a type from 1 to 4 and that no path joins two gardens of the same type.
Complexity: O(n + m) time and space, where m is the number of paths.
class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
graph = [[] for _ in range(n)]
for x, y in paths:
graph[x - 1].append(y - 1)
graph[y - 1].append(x - 1)
answer = [0] * n
for x in range(n):
# At most 3 neighbours use at most 3 of the 4 types, so a free type always exists.
used = {answer[y] for y in graph[x]}
answer[x] = next(c for c in range(1, 5) if c not in used)
return answer