# Leetcode-695. Max Area of Island 岛屿的最大面积 （矩阵DFS）

### 题目

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example:

[[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]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

### 思路及代码

#### DFS

class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
def dfs(row, col):
if row < 0 or col < 0 or row >= m or col >= n or not grid[row][col]:
return 0
grid[row][col] = 0
return dfs(row-1, col) + \
dfs(row+1, col) + \
dfs(row, col-1) + \
dfs(row, col+1) + 1

if not grid:
return 0
m = len(grid)
n = len(grid[0])
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j]:
ans = max(ans, dfs(i,j))
return ans


### 复杂度

T = $O(mn)$
S = $O(mn)$

02-23 892

10-08 2285

12-06 140

05-21 37

04-09 103

04-13 29

04-07 30

05-11 40

04-19

03-17 49

04-17 28

04-05 89

03-17 32

03-19 101

04-02 34

03-15 26

03-15 22

03-15 82

03-16 45

03-22 22

03-22 17

08-02 163

03-19 82万+

04-14 60万+

02-28 1万+

03-01 14万+

03-08 7万+

04-25 7万+

#### 总结了 150 余个神奇网站，你不来瞅瞅吗？

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客