463. Island Perimeter

2017-10-10  本文已影响0人  冷殇弦

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
上一篇 下一篇

猜你喜欢

热点阅读