Leetcode刷题岛屿的最大面积
Posted 外部存储设备
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode刷题岛屿的最大面积相关的知识,希望对你有一定的参考价值。
题目:https://leetcode-cn.com/problems/max-area-of-island/
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
# 遇到1后,对小岛进行广度优先搜索计算面积,并将遍历过的小岛沉没,避免再次计算
height = len(grid)
length = len(grid[0])
def get_area(x, y):
# 广度优先搜索求面积
area = 1
queue = [(x, y)]
grid[x][y] = 0
while queue:
i, j = queue.pop(0)
# 上
if i-1 >= 0 and grid[i-1][j] == 1:
area += 1
queue.append((i-1, j))
grid[i - 1][j] = 0
# 下
if i+1 < height and grid[i+1][j] == 1:
area += 1
queue.append((i+1, j))
grid[i + 1][j] = 0
# 左
if j-1 >= 0 and grid[i][j-1] == 1:
area += 1
queue.append((i, j-1))
grid[i][j - 1] = 0
# 右
if j+1 < length and grid[i][j+1] == 1:
area += 1
queue.append((i, j+1))
grid[i][j + 1] = 0
return area
max_area = 0
for i in range(height):
for j in range(length):
if grid[i][j] == 1:
area = get_area(i, j)
if area > max_area:
max_area = area
return max_area
以上是关于Leetcode刷题岛屿的最大面积的主要内容,如果未能解决你的问题,请参考以下文章