题解 | #岛屿数量#
岛屿数量
https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
class Solution { public: void dfs(vector<vector<char>> &grid, int r, int c) { int rows = grid.size(); int cols = grid[0].size(); // 边界检查 if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0') return; grid[r][c] = '0'; dfs(grid, r - 1, c); // 上 dfs(grid, r + 1, c); // 下 dfs(grid, r, c - 1); // 左 dfs(grid, r, c + 1); // 右 } int solve(vector<vector<char>> &grid) { int rows = grid.size(); if (rows == 0) return 0; int cols = grid[0].size(); int island_num = 0; // 逐个格子进行检查 for (int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) if (grid[i][j] == '1') { dfs(grid, i, j); island_num++; } return island_num; } };