自己寫的:
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