Simple Java Recursive Solution


  • 1
    C
     public int numIslands(char[][] grid) {
            if(grid.length==0)
                return 0;
            int rows =grid.length;
            int cols = grid[0].length;
            boolean[][] check = new boolean[rows][cols];
            int count=0;
            for(int i=0; i<rows; i++){
                for(int j=0; j<cols; j++){
                    if(grid[i][j]=='1' && !check[i][j]){
                        count++;
                        invalidateAdjacent(grid,check,i,j);
                    }
                }
            }
            return count;
        }
        
        public void invalidateAdjacent(char[][] g, boolean[][] b, int r, int c){
            if(r>=g.length ||c>=g[0].length || r<0|| c<0 || g[r][c]=='0' ||b[r][c])
                return;
            b[r][c] =true;
            invalidateAdjacent(g,b,r-1,c);
            invalidateAdjacent(g,b,r+1,c);
            invalidateAdjacent(g,b,r,c-1);
            invalidateAdjacent(g,b,r,c+1);
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.