Java. Recursive. Easy. some Comments. [4ms]


  • 0
    H
    public class Solution {
        public int numIslands(char[][] grid) {
            if(grid.length==0) return 0;
            int count=0;
            
            //Reduce territory size
            for(int i=0; i<grid.length; i++){
                for(int j=0; j<grid[0].length; j++){
                    
                    if(grid[i][j]=='1'){    //if territory is found
                        reduce(grid, i, j);     //recursively make all the territory '0'
                        grid[i][j]='1';         //recover starting point with '1'
                        count++;                //then count++
                    } 
                }
            }
            return count;
        }
    
        private void reduce(char [][] grid, int row, int col){
            
            if(grid[row][col]=='1'){
                
                //make it '0'. Need to do it first before recursive in order to avoid stack overflow.
                grid[row][col]='0';
                
                //recursively delete up
                if((row-1)>=0) reduce(grid, row-1, col);
                
                //recursively delete down
                if((row+1)<grid.length) reduce(grid, row+1, col);
                
                //recursively delete left
                if((col-1)>=0) reduce(grid, row, col-1);
                
                //recursively delete right
                if((col+1)<grid[0].length) reduce(grid, row, col+1);
            }
                
        }
    }
    

Log in to reply
 

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