Problem Description
Given n gardens and a list of bidirectional paths connecting them, assign one of four flower types (1, 2, 3, or 4) to each garden such that no two connected gardens have the same flower type. Each garden has at most three paths connecting it to other gardens. An answer is guaranteed to exist.
Key Insights
- The problem can be modeled as a graph coloring problem where each garden is a node.
- Since every garden can have at most 3 adjacent gardens and we have 4 flower types, there will always be at least one available flower type for each garden.
- A greedy approach (iterating through each garden and choosing a flower type that is not used by its neighbors) is sufficient.
- The graph is undirected, so each edge connects two nodes, and the validity check must be performed in both directions.
Space and Time Complexity
Time Complexity: O(n + m) where n is the number of gardens and m is the number of paths. Space Complexity: O(n + m) for storing the adjacency list and the result array.
Solution
The solution involves constructing an adjacency list from the paths to represent the graph. Then, iterate through each garden from 1 to n and for each garden, check the flower types already assigned to its neighboring gardens. Choose the smallest flower type from the set {1, 2, 3, 4} that is not used by its neighbors and assign it. This greedy algorithm works because each garden has at most 3 neighbors, ensuring that at least one type remains available.