200. Number of Islands(岛屿数量)
题目大意
Given an m x n
2D binary grid grid
which represents a map of '1’s (land) and '0’s (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
中文释义
给定一个 m x n
的二维二进制网格 grid
,它代表了由 ‘1’(陆地)和 ‘0’(水域)构成的地图,返回岛屿的数量。
一个岛屿被水包围,并且是通过水平或垂直连接相邻的陆地形成的。你可以假设网格的所有四个边界都被水包围。
示例
- 示例 1:
- 输入:
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
- 输出:
1
- 输入:
- 示例 2:
- 输入:
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
- 输出:
3
- 输入:
限制条件
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
是 ‘0’ 或 ‘1’。
解题思路
使用深度优先搜索(DFS)来解决问题。遍历网格,对每个未访问的 ‘1’ 节点执行 DFS 搜索,以找出岛屿的边界。
步骤说明
- 初始化一个标记节点是否已访问的二维布尔数组
is_visited
。 - 对网格中的每个节点进行遍历:
- 如果节点是 ‘1’ 且未被访问,则执行 DFS。
- DFS 会标记所有与当前节点相连的 ‘1’ 节点为已访问。
- 每次执行 DFS 时,岛屿数量增加。
- 返回岛屿的总数量。
代码
class Solution {
public:
void dfs(int i, int j, vector<vector<char>>& grid, vector<vector<bool>>& is_visited) {
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size()) return;
if (is_visited[i][j] || grid[i][j] == '0') return;
is_visited[i][j] = true;
dfs(i - 1, j, grid, is_visited);
dfs(i + 1, j, grid, is_visited);
dfs(i, j - 1, grid, is_visited);
dfs(i, j + 1, grid, is_visited);
}
int numIslands(vector<vector<char>>& grid) {
int ans = 0;
int n = grid.size(), m = grid[0].size();
vector<vector<bool>> is_visited(n, vector<bool>(m, false));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1' && !is_visited[i][j]) {
dfs(i, j, grid, is_visited);
ans++;
}
}
}
return ans;
}
};