Skip to content

Commit 97cd180

Browse files
author
Shuo
authored
Merge pull request #524 from openset/develop
Add: Flower Planting With No Adjacent
2 parents d7f3243 + c5aa341 commit 97cd180

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package flower_planting_with_no_adjacent
2+
3+
func gardenNoAdj(N int, paths [][]int) []int {
4+
ans, adjGarden, flowerUsed := make([]int, N), make([][]int, N), make([][4]bool, N)
5+
for _, path := range paths {
6+
if path[0] > path[1] {
7+
path[0], path[1] = path[1], path[0]
8+
}
9+
adjGarden[path[0]-1] = append(adjGarden[path[0]-1], path[1]-1)
10+
}
11+
for i := 0; i < N; i++ {
12+
for flower, used := range flowerUsed[i] {
13+
if !used {
14+
ans[i] = flower + 1
15+
break
16+
}
17+
}
18+
for _, garden := range adjGarden[i] {
19+
flowerUsed[garden][ans[i]-1] = true
20+
}
21+
}
22+
return ans
23+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package flower_planting_with_no_adjacent
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
n int
10+
paths [][]int
11+
expected []int
12+
}
13+
14+
func TestGardenNoAdj(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
n: 3,
18+
paths: [][]int{
19+
{1, 2},
20+
{2, 3},
21+
{3, 1},
22+
},
23+
expected: []int{1, 2, 3},
24+
},
25+
{
26+
n: 4,
27+
paths: [][]int{
28+
{1, 2},
29+
{3, 4},
30+
},
31+
expected: []int{1, 2, 1, 2},
32+
},
33+
{
34+
n: 4,
35+
paths: [][]int{
36+
{1, 2},
37+
{2, 3},
38+
{3, 4},
39+
{4, 1},
40+
{1, 3},
41+
{2, 4},
42+
},
43+
expected: []int{1, 2, 3, 4},
44+
},
45+
}
46+
for _, tc := range tests {
47+
output := gardenNoAdj(tc.n, tc.paths)
48+
if !reflect.DeepEqual(output, tc.expected) {
49+
t.Fatalf("input: %v, output: %v, expected: %v", tc.n, output, tc.expected)
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)