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
| func islandPerimeter(grid [][]int) int {
if len(grid) == 0 {
return 0
}
row := len(grid)
col := len(grid[0])
perimeter := 0
for r := 0; r < row; r++ {
for c := 0; c < col; c++ {
if grid[r][c] == 1 {
// 检查四个方向
perimeter += 4 // 每个陆地单元初始周长为4
if r > 0 && grid[r-1][c] == 1 { // 上
perimeter -= 1
}
if r < row-1 && grid[r+1][c] == 1 { // 下
perimeter -= 1
}
if c > 0 && grid[r][c-1] == 1 { // 左
perimeter -= 1
}
if c < col-1 && grid[r][c+1] == 1 { // 右
perimeter -= 1
}
}
}
}
return perimeter
}
|