自己写的:
class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: # 初始化周长计数器 count = 0 # 遍历二维网格的行 for i in range(len(grid)): # 遍历二维网格的列 for j in range(len(grid[i])): # 如果当前位置有陆地(值为1) if grid[i][j] == 1: # 增加周长计数器4,因为陆地的四周都有边界 count += 4 # 检查上方是否有陆地,若有则减去一条边 if i - 1 >= 0 and grid[i - 1][j] == 1: count -= 1 # 检查下方是否有陆地,若有则减去一条边 if i + 1 <= len(grid) - 1 and grid[i + 1][j] == 1: count -= 1 # 检查左侧是否有陆地,若有则减去一条边 if j - 1 >= 0 and grid[i][j - 1] == 1: count -= 1 # 检查右侧是否有陆地,若有则减去一条边 if j + 1 <= len(grid[0]) - 1 and grid[i][j + 1] == 1: count -= 1 # 返回最终周长计数 return count
标签:count,陆地,周长,int,岛屿,Leedcode,grid,减去 From: https://www.cnblogs.com/yyyjw/p/18184123