|
| 1 | +classSolution { |
| 2 | +privatefinalint[][]DIRS = {{1,0}, {0,1}, {-1,0}, {0, -1}}; |
| 3 | + |
| 4 | +publicintcountSubIslands(int[][]grid1,int[][]grid2) { |
| 5 | +intnumRows =grid1.length; |
| 6 | +intnumCols =grid1[0].length; |
| 7 | +intsubIslandCount =0; |
| 8 | +boolean[][]visited =newboolean[numRows][numCols]; |
| 9 | +for (inti =0;i <numRows;i++) { |
| 10 | +for (intj =0;j <numCols;j++) { |
| 11 | +if (!visited[i][j] &&grid2[i][j] ==1) { |
| 12 | +Queue<int[]>queue =newLinkedList<>(); |
| 13 | +queue.add(newint[]{i,j}); |
| 14 | +booleanisSubisland =true; |
| 15 | +while (!queue.isEmpty()) { |
| 16 | +int[]removed =queue.remove(); |
| 17 | +intx =removed[0]; |
| 18 | +inty =removed[1]; |
| 19 | +if (visited[x][y]) { |
| 20 | +continue; |
| 21 | + } |
| 22 | +if (grid1[x][y] !=1) { |
| 23 | +isSubisland =false; |
| 24 | + } |
| 25 | +visited[x][y] =true; |
| 26 | +for (int[]dir :DIRS) { |
| 27 | +intnewX =x +dir[0]; |
| 28 | +intnewY =y +dir[1]; |
| 29 | +if (newX >=0 &&newY >=0 &&newX <numRows &&newY <numCols && !visited[newX][newY] &&grid2[newX][newY] ==1) { |
| 30 | +queue.add(newint[]{newX,newY}); |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | +if (isSubisland) { |
| 35 | +subIslandCount++; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | +returnsubIslandCount; |
| 41 | + } |
| 42 | +} |