leetcode 463. 岛屿的周长

题解

判断代表陆地点的上下左右点对应的值,出界或为零则周长加一

示例代码(go)

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
func islandPerimeter(grid [][]int) int {
res := 0
m := len(grid)
if m == 0 {
return res
}
n := len(grid[0])

for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
if i-1 < 0 || grid[i-1][j] == 0 {
res++
}
if i+1 >= m || grid[i+1][j] == 0 {
res++
}
if j-1 < 0 || grid[i][j-1] == 0 {
res++
}
if j+1 >= n || grid[i][j+1] == 0 {
res++
}
}
}
}
return res
}