1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { private final static int[][] DIRECTIONS = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public int countSubIslands(int[][] grid1, int[][] grid2) { boolean[][] visited = new boolean[grid2.length][grid2[0].length]; int ans = 0; for (int i = 0; i < grid2.length; i++) { for (int j = 0; j < grid2[0].length; j++) { if (grid2[i][j] == 1 && !visited[i][j]) { if (dfs(grid1, grid2, i, j, visited)) { ans += 1; } } } } return ans; }
private boolean dfs(int[][] grid1, int[][] grid2, int row, int col, boolean[][] visited) { boolean coverAll = true; if (grid1[row][col] != 1) { coverAll = false; } visited[row][col] = true; for (int[] direction : DIRECTIONS) { int newRow = row + direction[0]; int newCol = col + direction[1]; if (!isOutOfBound(grid2, newRow, newCol) && grid2[newRow][newCol] == 1 && !visited[newRow][newCol]) { if (!dfs(grid1, grid2, newRow, newCol, visited)) { coverAll = false; } } } return coverAll; }
private boolean isOutOfBound(int[][] grid2, int row, int col) { return row < 0 || col < 0 || row >= grid2.length || col >= grid2[0].length; } }
|