[LeetCode&Python] Problem 463. Island Perimeter

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:

 

We can consider a bigger grid:

0  0 0 0 0  0
0[[0,1,0,0] 0 0 [1,1,1,0] 0 0 [0,1,0,0] 0 0 [1,1,0,0]]0
0 0 0 0 0 0

We can just check the 0s in the grid. If there is a 1 next to it, we add one to the answer.

class Solution:
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m=len(grid)
        n=len(grid[0])
        ans=0
        
        for row in range(-1,m+1):
            for column in range(-1,n+1):
                if row==-1 or column==-1 or row==m or column==n or grid[row][column]==0:
                    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
                        newR,newC=row+d[0],column+d[1]
                        if 0<=newR<m and 0<=newC<n and grid[newR][newC]==1:
                            ans+=1
        
        return ans

  


posted on 2018-10-11 13:34  chiyeung  阅读(82)  评论(0编辑  收藏  举报

导航