1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
func pondSizes(land [][]int) []int {
if len(land) == 0 || len(land[0]) == 0 {
return []int{}
}
h, w := len(land), len(land[0])
dirs := [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}}
var bfs func(x, y int) int
bfs = func(x, y int) int {
var queue [][2]int
queue = append(queue, [2]int{x, y})
land[x][y] = 1
cnt := 1
for len(queue) > 0 {
curX, curY := queue[0][0], queue[0][1]
queue = queue[1:]
for i := 0; i < len(dirs); i++ {
dx, dy := dirs[i][0], dirs[i][1]
nx, ny := curX+dx, curY+dy
if nx >= 0 && nx < h && ny >= 0 && ny < w && land[nx][ny] == 0 {
land[nx][ny] = 1
queue = append(queue, [2]int{nx, ny})
cnt++
}
}
}
return cnt
}
var ans []int
for x := 0; x < h; x++ {
for y := 0; y < w; y++ {
if land[x][y] == 0 {
ans = append(ans, bfs(x, y))
}
}
}
sort.Ints(ans)
return ans
}
|