Flower Planting With No Adjacent

Similar Problems:

- CheatSheet: Leetcode For Code Interview
- CheatSheet: Common Code Problems & Follow-ups
- Tag: #greedy, #array, #inspiring

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.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

- Solution:

// https://code.dennyzhang.com/flower-planting-with-no-adjacent // Basic Ideas: greedy // Examine all the neighbors, and take the first available color // Complexity: Time O(n^2), Space O(n^2) func gardenNoAdj(N int, paths [][]int) []int { l := make([][]int, N) res := make([]int, N) for _, path := range paths { n1, n2 := path[0]-1, path[1]-1 l[n1] = append(l[n1], n2) l[n2] = append(l[n2], n1) } for n1, _ := range res { isUsed := make([]bool, 5) for _, n2 := range l[n1] { isUsed[res[n2]] = true } // take the first available color for i:=1; i<5; i++ { if !isUsed[i] { res[n1] = i break } } } return res }