题目: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.
题目的大意就是用一个二维数组去模拟一个地图,1代表陆地,0代表水,每一个cell的边长为1,于是给定一个矩阵,求陆地的周长。
很形象的给了一个图:
例如:Input: [[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
这个题目还是蛮简单的,提供一种思路,我们可以将水和陆地看成两种不同的颜色,于是当我们遍历时,遇到颜色不一样就周长就加一,那么这个问题就解决了。不说了,上代码。
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = len(grid)
if(rows>0):
cols=len(grid[0])
perimeter = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
if j-1 < 0 or grid[i][j-1] == 0:
perimeter += 1
if j+1 >= cols or grid[i][j+1] == 0:
perimeter += 1
if i-1 < 0 or grid[i-1][j] == 0:
perimeter += 1
if i+1 >= rows or grid[i+1][j] == 0:
perimeter += 1
return perimeter
if __name__ == "__main__":
'''
grid = [[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
'''
grid = [[1],[0]]
print Solution().islandPerimeter(grid)
当然,你如果想装装逼,用几行代码就搞定的话也是可以的
def islandPerimeter2(self,grid):
rows, cols, perimeter = len(grid), len(grid[0]), 0
def get(r, c):
return grid[r][c] if 0 <= r < rows and 0 <= c < cols else 0
return sum( (get(r,c)^get(r-1,c)) + (get(r,c)^get(r,c-1))
for r in range(rows+1) for c in range(cols+1))
就是用到了一个小trick,异或,想必这里也不用解释了吧,一看就懂的~ 不过对编码能力还是有点要求的,我个人还是喜欢第一种写法呀~