题目地址:https://leetcode.com/problems/max-area-of-island/description/
大意:这题跟200题很想,200题是求“岛”的个数,这一题是求“岛”的最大面积。可以参考200题(https://www.jianshu.com/p/4da701d8b5fa)
思路:
同样的,用DFS,每次遍历的时候比较一下当前面积和最大面积的,如果当前面积大,就用当前面积取代最大面积。重点还是DFS方法。
# 695. Max Area of Island
class Solution:
area = 0
max = 0
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
for y in range(m):
for x in range(n):
self.area = 0
if grid[y][x] == 1:
self.__dfs(grid, x, y, n, m)
return self.max
def __dfs(self,grid,x,y,n,m):
if x<0 or y<0 or x >= n or y>=m or grid[y][x] == 0:
return
grid[y][x] = 0
self.area = self.area +1
self.__dfs(grid, x + 1, y, n, m)
self.__dfs(grid, x - 1, y, n, m)
self.__dfs(grid, x, y + 1, n, m)
self.__dfs(grid, x, y - 1, n, m)
if self.area > self.max:
self.max = self.area