Flower Planting With No Adjacent
The problem asks us to assign flower types to each garden, ensuring that no two connected gardens have the same flower type. Since there are only four flower types and each garden has at most three paths, we can always find a solution.
Solution
- Create a graph to represent the connections between the gardens.
- For each garden, look at the neighboring gardens and find the flower types already assigned to them.
- Assign the first flower type that hasn’t been assigned to any neighboring garden.
|
|
Explanation
- We first build a graph to represent the connections between the gardens.
- Then we iterate through each garden, look at the flower types assigned to its neighboring gardens, and choose the first type not used by its neighbors.
- Since there are at most three neighbors and four flower types, we can always find a suitable type.
The time complexity of this solution is O(n), where n is the number of gardens, and the space complexity is also O(n), considering the graph storage and result array.
title: Flower Planting With No Adjacent tags: map filter graph 1-based-array-indexing adjacency-list
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.
Input:
n - garden number
paths - path between two gardens
|
|