leetcode695-dfs
/**
<p>给你一个大小为 <code>m x n</code> 的二进制矩阵 <code>grid</code> 。</p>
<p><strong>岛屿</strong> 是由一些相邻的 <code>1</code> (代表土地) 构成的组合,这里的「相邻」要求两个 <code>1</code> 必须在 <strong>水平或者竖直的四个方向上 </strong>相邻。你可以假设 <code>grid</code> 的四个边缘都被 <code>0</code>(代表水)包围着。</p>
<p>岛屿的面积是岛上值为 <code>1</code> 的单元格的数目。</p>
<p>计算并返回 <code>grid</code> 中最大的岛屿面积。如果没有岛屿,则返回面积为 <code>0</code> 。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg" style="width: 500px; height: 310px;" />
<pre>
<strong>输入:</strong>grid = [[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]]
<strong>输出:</strong>6
<strong>解释:</strong>答案不应该是 <code>11</code> ,因为岛屿只能包含水平或垂直这四个方向上的 <code>1</code> 。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>grid = [[0,0,0,0,0,0,0,0]]
<strong>输出:</strong>0
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>grid[i][j]</code> 为 <code>0</code> 或 <code>1</code></li>
</ul>
<div><div>Related Topics</div><div><li>深度优先搜索</li><li>广度优先搜索</li><li>并查集</li><li>数组</li><li>矩阵</li></div></div><br><div><li>👍 800</li><li>👎 0</li></div>
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
//淹没岛屿的同时计算面积
public int maxAreaOfIsland(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(grid[i][j]==1){
res = Math.max(res,dfs(grid,i,j));
}
}
}
return res;
}
int dfs(int[][] grid, int i, int j) {
int m = grid.length;
int n = grid[0].length;
if (i < 0 || j < 0 || i >= m || j >= n) {
return 0;
}
if (grid[i][j] == 0) {
return 0;
}
grid[i][j] = 0;
return dfs(grid, i + 1, j) + dfs(grid, i, j + 1) + dfs(grid, i - 1, j) + dfs(grid, i, j - 1) + 1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
不恋尘世浮华,不写红尘纷扰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理