You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
Example:
[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 Explanation: The perimeter is the 16 yellow stripes in the image below:
class Solution(object):
def islandPerimeter(self, grid):
res = 0
for i in grid:
res += sum(i)
g= grid
res *= 4
i,j = 0,0
while i < len(g):
j = 0
while j < len(g[0]):
if j + 1< len(g[0]) and g[i][j] == 1 and g[i][j+1] == 1:
res -= 2
j += 1
i += 1
i,j = 0,0
while i < len(g[0]):
j = 0
while j < len(g):
if j + 1 < len(g) and g[j][i] == 1 and g[j+1][i] == 1:
res -= 2
j += 1
i += 1
return res

本文介绍了一种简单算法,用于计算二维网格中岛屿的周长。通过遍历网格确定陆地单元格数量,并调整相邻陆地之间的连接数来精确计算周长。

394

被折叠的 条评论
为什么被折叠?



