当前位置: 面试刷题>> 岛屿数量(经典算法150题)


### 题目描述 给定一个由 `'1'`(表示陆地)和 `'0'`(表示水域)组成的二维网格,计算网格中岛屿的数量。岛屿总是被水域包围,并且每块岛屿由水平方向和垂直方向上相邻的陆地组成。此外,你可以假设该网格的四条边均被水域包围。 ### 示例 **输入**: ``` 11110 11010 11000 00000 ``` **输出**: 1 **解释**: 只有一个岛屿,由左上角的四个 '1' 组成。 ### PHP 示例代码 ```php function numIslands($grid) { if (empty($grid) || empty($grid[0])) { return 0; } $rows = count($grid); $cols = strlen($grid[0]); $count = 0; for ($i = 0; $i < $rows; $i++) { for ($j = 0; $j < $cols; $j++) { if ($grid[$i][$j] == '1') { dfs($grid, $i, $j); $count++; } } } return $count; } function dfs(&$grid, $i, $j) { $rows = count($grid); $cols = strlen($grid[0]); if ($i < 0 || $j < 0 || $i >= $rows || $j >= $cols || $grid[$i][$j] != '1') { return; } $grid[$i][$j] = '#'; // 标记为已访问 dfs($grid, $i - 1, $j); // 上 dfs($grid, $i + 1, $j); // 下 dfs($grid, $i, $j - 1); // 左 dfs($grid, $i, $j + 1); // 右 } // 示例用法 $grid = [ "11110", "11010", "11000", "00000" ]; echo numIslands($grid); // 输出: 1 ``` ### Python 示例代码 ```python def numIslands(grid): if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) count = 0 for i in range(rows): for j in range(cols): if grid[i][j] == '1': dfs(grid, i, j) count += 1 return count def dfs(grid, i, j): rows, cols = len(grid), len(grid[0]) if i < 0 or j < 0 or i >= rows or j >= cols or grid[i][j] != '1': return grid[i][j] = '#' # 标记为已访问 dfs(grid, i - 1, j) # 上 dfs(grid, i + 1, j) # 下 dfs(grid, i, j - 1) # 左 dfs(grid, i, j + 1) # 右 # 示例用法 grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] print(numIslands(grid)) # 输出: 1 ``` ### JavaScript 示例代码 ```javascript function numIslands(grid) { if (!grid.length || !grid[0].length) { return 0; } let rows = grid.length; let cols = grid[0].length; let count = 0; for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (grid[i][j] === '1') { dfs(grid, i, j); count++; } } } return count; } function dfs(grid, i, j) { const rows = grid.length; const cols = grid[0].length; if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] !== '1') { return; } grid[i][j] = '#'; // 标记为已访问 dfs(grid, i - 1, j); // 上 dfs(grid, i + 1, j); // 下 dfs(grid, i, j - 1); // 左 dfs(grid, i, j + 1); // 右 } // 示例用法 const grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]; console.log(numIslands(grid)); // 输出: 1 ``` 这些示例代码均使用了深度优先搜索(DFS)算法来遍历并标记岛屿中的每个陆地,从而计算出岛屿的总数。
推荐面试题