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:
一块陆地有4个边,陆地个数*4给出边长的上界。这个上界中,每个陆地相邻的边都被算了2次,所以每当出现相邻的边都应该减2。为了避免查找重复,每块陆地我们只查看它的右侧和下方。
1 class Solution(object): 2 def islandPerimeter(self, grid): 3 """ 4 :type grid: List[List[int]] 5 :rtype: int 6 """ 7 8 m = len(grid) 9 n = len(grid[0]) 10 ans = 0 11 for row in range(m): 12 for col in range(n): 13 if grid[row][col] == 1: 14 ans += 4 15 if row < m-1 and grid[row+1][col] == 1: 16 ans -= 2 17 if col < n-1 and grid[row][col+1] == 1: 18 ans -= 2 19 return ans 20