// 每次递归将连在一块的岛屿设为0,且岛屿个数+1。 // grid.resize(M,vector<int>(N,0)); 二维数组初始化,M行N列都为0 class Solution { public: int dir[5] = {1 , 0, -1, 0, 1}; // 递归方向 void dfs(vector<vector<char>> &grid, int i, int j){ if(i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] == '0') return ; grid[i][j] = '0'; // 将经过的岛屿置为 0 for(int k = 0; k < 4;k ++){ dfs(grid, i + dir[k],j + dir[k+1]); } } int solve(vector<vector<char> >& grid) { // write code here int ans = 0; int N = grid.size(); int M = grid[0].size(); for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(grid[i][j] == '1'){ ans++; dfs(grid, i, j); } } } return ans; } };