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.

题目的大意就是用一个二维数组去模拟一个地图,1代表陆地,0代表水,每一个cell的边长为1,于是给定一个矩阵,求陆地的周长。

很形象的给了一个图:


例如:Input: [[0,1,0,0],
                      [1,1,1,0],
                      [0,1,0,0],
                      [1,1,0,0]]

        Output: 16

这个题目还是蛮简单的,提供一种思路,我们可以将水和陆地看成两种不同的颜色,于是当我们遍历时,遇到颜色不一样就周长就加一,那么这个问题就解决了。不说了,上代码。

 

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        rows = len(grid)
        if(rows>0):
            cols=len(grid[0])
        perimeter = 0
        
        for i in range(rows):
            for j in range(cols):
                if grid[i][j] == 1:
                    if j-1 < 0 or grid[i][j-1] == 0:
                        perimeter += 1
                    if j+1 >= cols or grid[i][j+1] == 0:
                        perimeter += 1
                    if i-1 < 0 or grid[i-1][j] == 0:
                        perimeter += 1
                    if i+1 >= rows or grid[i+1][j] == 0:
                        perimeter += 1
        return perimeter

if __name__ == "__main__":
    '''
    grid = [[0,1,0,0],
            [1,1,1,0],
            [0,1,0,0],
            [1,1,0,0]]
    '''
    grid = [[1],[0]]
    print Solution().islandPerimeter(grid)


当然,你如果想装装逼,用几行代码就搞定的话也是可以的

    def islandPerimeter2(self,grid):
        rows, cols, perimeter = len(grid), len(grid[0]), 0
        def get(r, c):
            return grid[r][c] if 0 <= r < rows and 0 <= c < cols else 0
        return sum( (get(r,c)^get(r-1,c)) + (get(r,c)^get(r,c-1))
                    for r in range(rows+1) for c in range(cols+1))
就是用到了一个小trick,异或,想必这里也不用解释了吧,一看就懂的~ 不过对编码能力还是有点要求的,我个人还是喜欢第一种写法呀~




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值