【leetcode】463. Island Perimeter【E】

175 篇文章 0 订阅
157 篇文章 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:

Subscribe to see which companies asked this question



算法很简单,其实就是一共多少个1 ,乘以4就是一共有多少条边,然后再看有多少个相邻的边,每条相邻的边,减2,就对了

比如上面这个图,一共7个1 ,共28条边,6条相邻的边,28-12 = 16




class Solution(object):
    def islandPerimeter(self, grid):
        
        res = 0
        
        for i in grid:
            res += sum(i)
        g= grid
        res *= 4
        
        i,j = 0,0
        
        while i < len(g):
            j = 0
            while j < len(g[0]):
                if j + 1< len(g[0]) and g[i][j] == 1 and g[i][j+1] == 1:
                    res -= 2
                j += 1
            i += 1
            
        i,j = 0,0
        while i < len(g[0]):
            j = 0
            while j < len(g):
                if j + 1 < len(g) and g[j][i] == 1 and g[j+1][i] == 1:
                    res -= 2
                j += 1
            i += 1
        return res    


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值