diff --git a/problems/flower-planting-with-no-adjacent/flower_planting_with_no_adjacent.go b/problems/flower-planting-with-no-adjacent/flower_planting_with_no_adjacent.go new file mode 100644 index 000000000..26ca114a8 --- /dev/null +++ b/problems/flower-planting-with-no-adjacent/flower_planting_with_no_adjacent.go @@ -0,0 +1,23 @@ +package flower_planting_with_no_adjacent + +func gardenNoAdj(N int, paths [][]int) []int { + ans, adjGarden, flowerUsed := make([]int, N), make([][]int, N), make([][4]bool, N) + for _, path := range paths { + if path[0] > path[1] { + path[0], path[1] = path[1], path[0] + } + adjGarden[path[0]-1] = append(adjGarden[path[0]-1], path[1]-1) + } + for i := 0; i < N; i++ { + for flower, used := range flowerUsed[i] { + if !used { + ans[i] = flower + 1 + break + } + } + for _, garden := range adjGarden[i] { + flowerUsed[garden][ans[i]-1] = true + } + } + return ans +} diff --git a/problems/flower-planting-with-no-adjacent/flower_planting_with_no_adjacent_test.go b/problems/flower-planting-with-no-adjacent/flower_planting_with_no_adjacent_test.go new file mode 100644 index 000000000..93b4de752 --- /dev/null +++ b/problems/flower-planting-with-no-adjacent/flower_planting_with_no_adjacent_test.go @@ -0,0 +1,52 @@ +package flower_planting_with_no_adjacent + +import ( + "reflect" + "testing" +) + +type caseType struct { + n int + paths [][]int + expected []int +} + +func TestGardenNoAdj(t *testing.T) { + tests := [...]caseType{ + { + n: 3, + paths: [][]int{ + {1, 2}, + {2, 3}, + {3, 1}, + }, + expected: []int{1, 2, 3}, + }, + { + n: 4, + paths: [][]int{ + {1, 2}, + {3, 4}, + }, + expected: []int{1, 2, 1, 2}, + }, + { + n: 4, + paths: [][]int{ + {1, 2}, + {2, 3}, + {3, 4}, + {4, 1}, + {1, 3}, + {2, 4}, + }, + expected: []int{1, 2, 3, 4}, + }, + } + for _, tc := range tests { + output := gardenNoAdj(tc.n, tc.paths) + if !reflect.DeepEqual(output, tc.expected) { + t.Fatalf("input: %v, output: %v, expected: %v", tc.n, output, tc.expected) + } + } +}