1905. Count Sub Islands

T: O(mn)
S: O(mn)
class Solution {
    private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid1.length;
        int n = grid1[0].length;

        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid2[i][j] == 1) {
                    Boolean[] result = new Boolean[1];
                    dfs(i, j, grid2, grid1, result);
                    if (result[0] == null) {
                        count++;
                    }
                }
            }
        }

        return count;
    }
    private void dfs(int i, int j, int[][] grid, int[][] grid1, Boolean[] result) {
        int m = grid.length;
        int n = grid[0].length;
        if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) {
            return;
        }
        if (grid1[i][j] == 0 && result[0] == null) {
            result[0] = false;
        }
        grid[i][j] = 0;
        for (int[] dir : DIRECTIONS) {
            dfs(i + dir[0], j + dir[1], grid, grid1, result);
        }
    }
}

/**
record all
sub-island position for island

then use position to see if there's 0 in (x, y)


use a result[0] to save the result (but entire island still need to traverse over and mark to 0!)

T: O(mn)
S: O(mn)
 */

Last updated