https://leetcode.cn/problems/max-area-of-island/
给你一个大小为 m x n 的二进制矩阵 grid 。
岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
岛屿的面积是岛上值为 1 的单元格的数目。
计算并返回 grid 中最大的岛屿面积。如果没有岛屿,则返回面积为 0 。
示例 1:
输入: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]]
输出:6
解释:答案不应该是 11 ,因为岛屿只能包含水平或垂直这四个方向上的 1 。
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(i, j):
if not 0 <= i < m or not 0 <= j < n:
return 0
if grid[i][j] == 0:
return 0
grid[i][j] = 0
return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1)
# def bfs(i, j):
# cur = 0
# q = [[i, j]]
# while q:
# [i, j] = q.pop(0)
# if not 0 <= i < m or not 0 <= j < n:
# continue
# if grid[i][j] == 0:
# continue
# grid[i][j] = 0
# cur += 1
# q += [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]
# return cur
cnt = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
cnt = max(cnt, dfs(i, j))
# cnt = max(cnt, bfs(i, j))
return cnt