1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// @Title: 岛屿的最大面积 (Max Area of Island)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 12 ms
// @Memory: 5.1 MB
func maxAreaOfIsland(grid [][]int) int {
	var maxArea int
	for i  := range grid {
		for j := range grid[0] {
			maxArea =  max(maxArea, dfs(grid,i,j))
		}
	}

	return maxArea
}

func dfs(grid [][]int, i,j int) int {
	if grid[i][j] == 0 {
		return 0
	}
	// 更新状态
	grid[i][j] = 0

	area := 1
	if i != 0  {
		area +=  dfs(grid, i-1,j)
	}
	if j != 0 {
		area += dfs(grid, i,j-1)
	}
	if i != len(grid)-1 {
	area+= dfs(grid,i+1,j)
	}
	if j != len(grid[0])-1 {
		area += dfs(grid,i,j+1)
	}
	return area

}

func max(a,b int) int {
	if a > b {
		return a
	}
	return b
}