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:

image.png

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        col = len(grid)
        row = len(grid[0])
        ans = 0
        for c in xrange(col):
            for r in xrange(row):
                if grid[c][r] == 0:
                    continue
                if grid[c][r] == 1:
                    ans += 4
                if c>0 and grid[c-1][r] == 1:
                    ans -= 1
                if r>0 and grid[c][r-1] == 1:
                    ans -= 1
                if c<col-1 and grid[c+1][r] == 1:
                    ans -= 1
                if r<row-1 and grid[c][r+1] == 1:
                    ans -= 1
        return ans
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容