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]]
Explanation: The perimeter is the 16 yellow stripes in the image below
Answer: 16
思路很简单,每次看看上下左右的邻居是不是1,如果有一个是的话,就减一,都是一,自然而然对周长没有贡献,如果都不是一,那就是另一个极端,对周长贡献是4。
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: list[list[int]]
:rtype: int
"""
r = 0
row = len(grid)
column = len(grid[0])
for i in xrange(row):
for j in xrange(column):
if grid[i][j] == 1:
count = 4
if 0 <= i - 1 < row and 0 <= j < column and grid[i - 1][j] == 1:
count -= 1
if 0 <= i + 1 < row and 0 <= j < column and grid[i + 1][j] == 1:
count -= 1
if 0 <= i < row and 0 <= j - 1 < column and grid[i][j - 1] == 1:
count -= 1
if 0 <= i < row and 0 <= j + 1 < column and grid[i][j + 1] == 1:
count -= 1
r += count
return r
if __name__ == '__main__':
print Solution().islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]])