题解 | #岛屿数量#
岛屿数量
https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 判断岛屿数量 * @param grid char字符型二维数组 * @return int整型 */ private void dfsZero(char[][] grid, int i, int j){ int m = grid.length; int n = grid[0].length; grid[i][j] = '0'; if(i-1>=0 && grid[i-1][j]=='1') dfsZero(grid, i-1, j); if(i+1<m && grid[i+1][j]=='1') dfsZero(grid, i+1, j); if(j-1>=0 && grid[i][j-1]=='1') dfsZero(grid, i, j-1); if(j+1<n && grid[i][j+1]=='1') dfsZero(grid, i, j+1); } public int solve (char[][] grid) { // write code here if(grid.length==0) return 0; int m = grid.length; int n = grid[0].length; int island = 0; for(int i=0; i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j]=='1'){ island++; dfsZero(grid, i, j); } } } return island; } }
递归的思想不止能用于树