Easy Solution using dfs


  • 0
    U

    Thanks to @tankztc

        public int islandPerimeter(int[][] grid) {
           int[] count=new int[1];
           int [][] dirs =new int[][] {{0,1},{1,0},{0,-1},{-1,0}};
           for(int i=0;i<grid.length;i++){
               for(int j=0;j<grid[0].length;j++){
                   if(grid[i][j]==1) dfs(grid,count,dirs,i,j);
                   }
           }
           return count[0];
        }
        
        public void dfs(int[][]grid,int[] count,int[][] dirs,int i,int j){
            for(int[]dir : dirs){
                int newR = i+dir[0];
                int newC = j+dir[1];
                if(newR<0 || newR>=grid.length || newC<0 || newC>=grid[0].length||grid[newR][newC]==0){ count[0]++;
                
                }
                
            }
            
        }
    }

Log in to reply
 

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