Python BFS 695. 岛屿的最大面积

Introduction

原题695. 岛屿的最大面积,常规题了,小小bfs一下。

from collections import deque
class Solution(object):
    def __int__(self):
        self.count = 0

    def maxAreaOfIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        if not grid: return 0

        m, n = len(grid), len(grid[0])
        visited = [[False for _ in range(n)] for _ in range(m)]
        result = 0

        for i in range(m):
            for j in range(n):
                if not visited[i][j] and grid[i][j] == 1:
                    # 每一个新岛屿
                    self.count = 0
                    print(f'{self.count}')
                    self.bfs(grid, visited, i, j)
                    result = max(result, self.count)

        return result

    def bfs(self, grid, visited, i, j):
        self.count += 1
        visited[i][j] = True

        queue = deque([(i, j)])
        while queue:
            x, y = queue.popleft()
            for new_x, new_y in [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]:
                if self.is_within_scope(grid, new_x, new_y) and not visited[new_x][new_y] \
                        and grid[new_x][new_y] == 1:
                    visited[new_x][new_y] = True
                    self.count += 1
                    queue.append((new_x, new_y))

    def is_within_scope(self, grid, x, y):
        if 0 <= x < len(grid) and 0 <= y < len(grid[0]):
        # if 0 <= x < len(grid[0]) and 0 <= y < len(grid):
            return True
        else:
            return False

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

这里有个问题需要说明一下,在数组初始化的时候,常常会有两种方法,如下:

# method1
arr = [0 for _ in range(n)]

# method2
arr = [0] * n

事实上method2会更快一点,所以平常我也是使用method2来进行数组的初始化,今天做这题的时候,我visited = [[False] * n] * m初始化了一个二维数组,然后就一直出问题,无法得到正确答案!去网上一搜,原来才发现这样做是不对的,因为 [0] * n是一个一维数组的对象,*m的话只是把对象的引用复制了m次,如果我修改visited[0][0]visited[1][0]会同时发生改变!正确的方法还是应该遵循method1

visited = [[False for _ in range(n)] for _ in range(m)]

现在我写一维数组也不想用method2了…

References

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zeeland

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值