463. 岛屿的周长
https://leetcode-cn.com/problems/island-perimeter/
解法一:
思路:先数有几个land(棕色),不考虑重复边的话,总边数=land*4. 然而有重复边,即相邻两个land的公共边被重复计算了两次,记总的重复边为repeat,则最终结果为land*4-repeat*2
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
land, repeat = 0, 0 #land和重复边计数
row, col = len(grid), len(grid[0])
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
land += 1
if j+1 < col and grid[i][j+1] == 1: #右侧有land
repeat += 1
if i+1 < row and grid[i+1][j] == 1: #下侧有land
repeat += 1
return land*4 - repeat*2
最后更新于