题解 | #岛屿数量#
岛屿数量
https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
import java.util.*; public class Solution { /** * 判断岛屿数量 * @param grid char字符型二维数组 * @return int整型 */ public int solve (char[][] grid) { // write code here if(grid.length==0){ return 0; } int row=grid.length; int col=grid[0].length; boolean[][] mark=new boolean[row][col]; int k=0; for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(grid[i][j]=='1'&&!mark[i][j]){ dfs(grid,i,j,row,col,mark); k++; } } } return k; } public void dfs(char[][]grid,int i,int j,int row,int col,boolean[][] mark){ if(i<0||j<0||i>=row||j>=col||mark[i][j]||grid[i][j]=='0'){ return; } mark[i][j]=true; dfs(grid,i-1,j,row,col,mark); dfs(grid,i,j-1,row,col,mark); dfs(grid,i+1,j,row,col,mark); dfs(grid,i,j+1,row,col,mark); } }