463. Island Perimeter

来源:互联网 发布:淘宝拒签会自动退款吗 编辑:程序博客网 时间:2024/06/05 07:43

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.

二重列表 同一列挨着的1减2  同一行挨着的1 减2


代码

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        b=0
        for x in grid:
            b+=x.count(1)
        cnt=0
        for i in range(0,len(grid)-1):
            for j in range(0,len(grid[i])):
                if grid[i][j]==1 and grid[i+1][j]==1:
                    cnt+=1
        for i in range(0,len(grid)):
            for j in range(0,len(grid[i])-1):
                if grid[i][j]==1 and grid[i][j+1]==1:
                    cnt+=1
        s=b*4-cnt*2
        return s
            

1 0
原创粉丝点击