We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
https://leetcode-cn.com/problems/max-area-of-island/
给定一个包含了一些 0 和 1 的非空二维数组 grid 。
一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。)
示例 1:
[[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]] 对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。
示例 2:
[[0,0,0,0,0,0,0,0]] 对于上面这个给定的矩阵, 返回 0。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/max-area-of-island 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
在之前探索过「被包围的岛屿」问题后,这个问题显得格外简单了。希望这个分类的题刷完,能让我对DFS有进一步的掌握。
DFS
/** * @param {number[][]} grid * @return {number} */ var maxAreaOfIsland = function (grid) { let yLen = grid.length; if (!yLen) return grid; let xLen = grid[0].length; let max = 0; for (let y = 0; y < yLen; y++) { for (let x = 0; x < xLen; x++) { if (grid[y][x] === 1) { let countRef = { current: 0 }; dfs(grid, y, x, countRef); if (countRef.current > max) { max = countRef.current; } } } } return max; }; function dfs(grid, y, x, countRef) { if (!grid[y] || !grid[y][x] || grid[y][x] === 0 || grid[y][x] === "COMPLETE") { return; } if (grid[y][x] === 1) { grid[y][x] = "COMPLETE"; countRef.current++; } dfs(grid, y - 1, x, countRef); dfs(grid, y + 1, x, countRef); dfs(grid, y, x - 1, countRef); dfs(grid, y, x + 1, countRef); }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
问题
https://leetcode-cn.com/problems/max-area-of-island/
给定一个包含了一些 0 和 1 的非空二维数组 grid 。
一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。)
示例 1:
[[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]]
对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。
示例 2:
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
感想
在之前探索过「被包围的岛屿」问题后,这个问题显得格外简单了。希望这个分类的题刷完,能让我对
DFS
有进一步的掌握。题解
The text was updated successfully, but these errors were encountered: