dfs,遍历矩阵找到值为 1 并进行搜索;
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param grid int整型二维数组
# @return int整型
#
class Solution:
def maxAreaIsland(self , grid: List[List[int]]) -> int:
# write code here
if not grid:
return 0
m, n = len(grid), len(grid[0])
dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def dfs(x, y, grid):
grid[x][y] = 0
res = 1
for i, j in dirs:
xi, yi = x + i, y + j
if 0 <= xi < m and 0 <= yi < n and grid[xi][yi] == 1:
res += dfs(xi, yi, grid)
return res
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
res = max(res, dfs(i, j, grid))
return res