LeetCode 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]]
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]])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章