import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 判断岛屿数量 * @param grid char字符型二维数组 * @return int整型 */ public int solve (char[][] grid) { // write code here int[][] tags = new int[grid.length][grid[0].length]; int count = 0; for (int i = 0; i < grid.length;i++) { for (int j = 0; j < grid[i].length;j++){ if (grid[i][j] == '1' && tags[i][j] != 1) { count++; } if (tags[i][j] != 1) { next(i,j,tags,grid); } } } return count; } public void next(int x,int y,int[][] tags,char[][] grid) { if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) { return ; } if(grid[x][y] == '1' && tags[x][y] != 1) { //next tags[x][y] = 1; next(x-1,y,tags,grid); next(x+1,y,tags,grid); next(x,y-1,tags,grid); next(x,y+1,tags,grid); } } }
1、遍历 每个节点,对于为‘1’并且未访问过的1的节点,为新增岛屿+1,并访问标记其邻居。