题目一:岛屿的周长
给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。
网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。
岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。
示例 :
输入:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
输出: 16
解释: 它的周长是下面图片中的 16 个黄色的边:
题目思路:
遍历每个1,看看周围有几个0,或者边界。
题目比较简单,做一个此类问题的入门。
class Solution(object):
# Computer perimes around [x,y]
def perimesAround(self, grid, x, y):
h, w = len(grid), len(grid[0])
perimes = 0
if y + 1 >= w or grid[x][y+1] == 0 : perimes += 1
if x + 1 >= h or grid[x+1][y] == 0 : perimes += 1
if y - 1 < 0 or grid[x][y-1] == 0 : perimes += 1
if x - 1 < 0 or grid[x-1][y] == 0 : perimes += 1
return perimes
def islandPerimeter(self, grid):
if len(grid) == 0 or len(grid[0]) == 0: return 0
h, w, perime = len(grid), len(grid[0]), 0
for i in range(h):
for j in range(w):
if grid[i][j] == 1:
perime +