leetcode695-dfs

/** <p>給你一個大小爲 <code>m x n</code> 的二進制矩陣 <code>grid</code> 。</p> <p><strong>島嶼</strong>&nbsp;是由一些相鄰的&nbsp;<code>1</code>&nbsp;(代表土地) 構成的組合,這裏的「相鄰」要求兩個 <code>1</code> 必須在 <strong>水平或者豎直的四個方向上 </strong>相鄰。你可以假設&nbsp;<code>grid</code> 的四個邊緣都被 <code>0</code>(代表水)包圍着。</p> <p>島嶼的面積是島上值爲 <code>1</code> 的單元格的數目。</p> <p>計算並返回 <code>grid</code> 中最大的島嶼面積。如果沒有島嶼,則返回面積爲 <code>0</code> 。</p> <p>&nbsp;</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>&nbsp;</p> <p><strong>提示:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章