My accepted solution


  • 0
    K
    public int numIslands(char[][] grid) {
        if(grid==null || grid.length ==0) return 0;
        int l1= grid.length;
        int l2= grid[0].length;
        int  [] [] temp = new int [l1] [l2];
        for(int i=0;i<l1;i++){
            for(int j=0;j<l2;j++){
                temp[i][j]=0;
            }
        }
        int islands = 0;
        for(int i=0;i<l1;i++){
            for(int j=0;j<l2;j++){
               if(grid[i][j]=='1' && !isVisited(i,j,temp)){
                   islands++;
                   
                   findIsalnds(i,j,grid,temp);
               } 
            }
        }
       return islands; 
    }
    
    public void findIsalnds(int i, int j, char[][] grid, int [] [] temp){
        if(isVisited(i,j,temp) || grid[i][j]=='0') return;
        temp[i][j]=1;
        findIsalnds(i,j-1,grid,temp);
        findIsalnds(i+1,j,grid,temp);
        findIsalnds(i-1,j,grid,temp);
        findIsalnds(i,j+1,grid,temp);
        
    }
    
    public boolean isVisited(int i, int j, int[] [] temp){
        if(i>=0 && j>=0 &&  i<temp.length && j<temp[0].length && temp[i][j]!=1){
            return false;
        }
        return true;
    }

Log in to reply
 

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