文章目录
- 题目描述
- 题解思路
- 题解代码
- 题目链接
题目描述
题解思路
我们遍历二维矩阵,如果当前格子的元素为1进行深度优先搜索,将搜索过的格子置为0,防止重复访问,然后对继续深度优先搜索上下左右中为1的格子
题解代码
func maxAreaOfIsland(grid [][]int) int {m, n := len(grid), len(grid[0])ans := 0var dfs func(i, j int) intdfs = func(i, j int) int {grid[i][j] = 0area := 1// 继续深度优先搜索上下左右为1的格子if i + 1 < m && grid[i + 1][j] == 1 {area += dfs(i + 1, j)}if i - 1 >= 0 && grid[i - 1][j] == 1 {area += dfs(i - 1, j)}if j - 1 >= 0 && grid[i][j - 1] == 1 {area += dfs(i, j - 1)}if j + 1 < n && grid[i][j + 1] == 1 {area += dfs(i, j + 1)}return area}for i := 0; i < m; i++ {for j := 0; j < n; j++ {if grid[i][j] == 1 {ans = max(ans, dfs(i, j))}}}return ans
}
题目链接
https://leetcode.cn/problems/max-area-of-island/description/