// 题解:使用深度优先遍历DFS,判断bad case条件 int numIslands(vector>& grid) { int rows = grid.size(); if (rows == 0) return; int cols = grid[0].size(); if (cols == 0) return; int nums_lands = 0; for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { if (grid[r][c] == '1') { nums_lands++; dfs(grid, r, c); } } } return nums_lands; } void dfs(vector>& grid, int r, int c) { if (!is_in_area(grid, r, c)) { return; } if (grid[r][c] != '1') { return; } grid[r][c] = '2'; dfs(grid, r - 1, c); dfs(grid, r + 1, c); dfs(grid, r, c + 1); dfs(grid, r, c - 1); } bool is_in_area(vector>& grid, int r, int c) { return r >= 0 && c <= 0 && r < grid.size() && c < grid[0].size(); } 2. 腐烂的橘子