leetcode-1254

/** <p>二維矩陣 <code>grid</code>&nbsp;由 <code>0</code>&nbsp;(土地)和 <code>1</code>&nbsp;(水)組成。島是由最大的4個方向連通的 <code>0</code>&nbsp;組成的羣,封閉島是一個&nbsp;<code>完全</code> 由1包圍(左、上、右、下)的島。</p> <p>請返回 <em>封閉島嶼</em> 的數目。</p> <p>&nbsp;</p> <p><strong>示例 1:</strong></p> <p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png" style="height: 151px; width: 240px;" /></p> <pre> <strong>輸入:</strong>grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] <strong>輸出:</strong>2 <strong>解釋:</strong> 灰色區域的島嶼是封閉島嶼,因爲這座島嶼完全被水域包圍(即被 1 區域包圍)。</pre> <p><strong>示例 2:</strong></p> <p><img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/11/07/sample_4_1610.png" style="height: 98px; width: 160px;" /></p> <pre> <strong>輸入:</strong>grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] <strong>輸出:</strong>1 </pre> <p><strong>示例 3:</strong></p> <pre> <strong>輸入:</strong>grid = [[1,1,1,1,1,1,1], &nbsp; [1,0,0,0,0,0,1], &nbsp; [1,0,1,1,1,0,1], &nbsp; [1,0,1,0,1,0,1], &nbsp; [1,0,1,1,1,0,1], &nbsp; [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] <strong>輸出:</strong>2 </pre> <p>&nbsp;</p> <p><strong>提示:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[0].length &lt;= 100</code></li> <li><code>0 &lt;= grid[i][j] &lt;=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>👍 144</li><li>👎 0</li></div> */ //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int closedIsland(int[][] grid) { int m = grid.length; int n = grid[0].length; //提前淹沒靠近陸地的島嶼 for (int i = 0; i < m; i++) { dfs(grid,i,0); dfs(grid,i,n-1); } //提前淹沒靠近陸地的島嶼 for (int j = 0; j < n; j++) { dfs(grid,0,j); dfs(grid,m-1,j); } int res = 0; for (int i = 0; i < m; i++) { for (int j = 0; j <n; j++) { if(grid[i][j]==0 ){ res++; dfs(grid,i,j); } } } return res; } void 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; } //是水 if(grid[i][j]==1){ return; } grid[i][j] = 1; // 淹沒上下左右的陸地 dfs(grid, i + 1, j); dfs(grid, i, j + 1); dfs(grid, i - 1, j); dfs(grid, i, j - 1); } } //leetcode submit region end(Prohibit modification and deletion)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章