Python BFS 695. 岛屿的最大面积
Posted 帅气的黑桃J
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于Python BFS 695. 岛屿的最大面积的主要内容,如果未能解决你的问题,请参考以下文章