LC463. 岛屿的周长

DFS

class Solution(object):
    def islandPerimeter(self,grid):
        count = 0
        def backtrack(count, x, y):
            grid[x][y] = 2
            for nx, ny in [(x - 1, y), (x + 1, y), (x, y + 1), (x, y - 1)]:
                if not(0<=nx<len(grid) and 0<= ny < len(grid[0])): #邻居边界就+1
                    count += 1
                if len(grid) > nx >= 0 and 0 <= ny < len(grid[0]) and grid[nx][ny]==0: #邻居是0就+1
                    count += 1
            return count
        xx = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    xx+=backtrack(count, i, j)
        return xx

遍历从左到右,从上到下,相邻的就只要计算右边和下面就行不会重复

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        x1,x2 = 0,0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    x1 += 1
                    if i < len(grid)-1 and grid[i+1][j] == 1:
                        x2 += 1
                    if j < len(grid[0])-1 and grid[i][j+1] == 1:
                        x2 += 1
        return 4*x1 - 2*x2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值