没看答案,陆地格的上下左右四个相邻方格中的水域格的数量即为该陆地格贡献的周长,用matrix二维数组替换掉grid,可避免过多的if else判断。
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
matrix = [[0] * (col+2) for _ in range(row+2)]
res = 0
for i in range(row):
for j in range(col):
matrix[i+1][j+1] = grid[i][j]
for i in range(1, row+1):
for j in range(1, col+1):
if matrix[i][j]:
neigbors = [matrix[i-1][j],
matrix[i+1][j],
matrix[i][j-1],
matrix[i][j+1]]
res += neigbors.count(0)
return res
不利用matrix版本,需要判断是否超出边界(边界外也是湖)。
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
res = 0
direction_x = [0, 1, 0, -1]
direction_y = [1, 0, -1, 0]
for i in range(row):
for j in range(col):
if grid[i][j]:
for k in range(4):
ox = i + direction_x[k]
oy = j + direction_y[k]
if ox < 0 or ox >= row or oy < 0 or oy >= col or not grid[ox][oy]:
res += 1
return res