1254. Number of Closed Islands

class Solution {
    private static final int[][] DIRS = {{0,1},{0,-1},{1,0},{-1,0}};
    public int closedIsland(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        // exclude island connected with edge 
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if ( (i == 0 || i == m-1 || j == 0 || j == n-1) && grid[i][j] == 0) {
                    dfs(grid, i, j);    
                }
            }
        }
        
        // count island numbers
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0) {
                    dfs(grid, i, j);
                    res++;
                }
            }
        }
        return res;
    }
    private void dfs(int[][] grid, int i, int j) {
        grid[i][j] = 2;
        for (int[] dir : DIRS) {
            int x = i + dir[0];
            int y = j + dir[1];
            if (!isValid(grid, x, y) || grid[x][y] != 0) {
                continue;
            }
            dfs(grid, x, y);
        }
    }
    private boolean isValid(int[][] grid, int i, int j) {
        return i >=0 && i < grid.length && j >= 0 && j < grid[0].length;
    }
}


/*
0s (land) and 1s (water)

island(0) surrouded by water(1)

how to check is sourrouded by water?

1. 
island connected with edge, cant be sorround water, 
so exclude island connected with edge
dfs from these islands, and 
mark these islands to 1(water) or flood fill (mark 2, also ok)

2. 
last is to dfs, cal the island number inside this board

in conclution: only cal islands are "not connected to edge"
*/

new version (filter in outside

Last updated

Was this helpful?