using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 判断岛屿数量 * @param grid char字符型二维数组 * @return int整型 */ public int solve (List<List<char>> grid) { int res = 0; for(int i = 0; i < grid.Count; i++){ for(int j = 0; j < grid[0].Count; j++){ if(grid[i][j] == '1'){ res++; grid[i][j] = '0'; dfs(grid, i, j); } } } return res; } public void dfs(List<List<char>> grid, int i, int j){ if(i > 0 && grid[i - 1][j] == '1'){ grid[i-1][j] = '0'; dfs(grid, i-1, j); } if(j > 0 && grid[i][j - 1] == '1'){ grid[i][j-1] = '0'; dfs(grid, i, j-1); } if(i < grid.Count - 1 && grid[i + 1][j] == '1'){ grid[i+1][j] = '0'; dfs(grid, i+1, j); } if(j < grid[0].Count - 1 && grid[i][j + 1] == '1'){ grid[i][j+1] = '0'; dfs(grid, i, j+1); } } }