刚开始学习Python编程,欢迎交流学习!
695.Max Area of Island
思路:涉及到数组的题目大部分都需要遍历,然后二维数组的话更加麻烦,所以在此类问题中为了更有效的解决问题(避免重复遍历),可以考虑使用递归的方法来解决。根据题目条件,满足条件的 “1”的位置可以顺藤摸瓜,依次遍历上下左右 4 个方向,若有 “1” 则计数加一,重点是已经遍历过为“1”的点,在计数后需要将其变为 “0”,避免下一次时重复计数,最后输出最大值即可。
提交代码:
class Solution:
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
row=len(grid)
col=len(grid[0])
max_size=0
def detection(i,j,size):
if not((0<= i< row and 0<= j < col)) or grid[i][j] ==0 :
return
size[0]+=1
grid[i][j]=0
direction=((0,1),(0,-1),(1,0),(-1,0))
for x in direction:
detection(i + x[0], j + x[1], size)
for i in range(row):
for j in range(col):
size=[0]
detection(i,j,size)
max_size = max(max_size,size[0])
return max_size