Java very Easy and elegant DFS Solution


  • 0
    K
    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            int res=0;
            int[][] dir= new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
           for(int i=0;i<grid.length;i++){
               for(int j=0;j<grid[0].length;j++){
                   if(grid[i][j]==1)
                       res=Math.max(res,dfs(grid,i,j,dir));
               }
           }
            return res;
        }
        
        public int dfs(int[][] grid,int i, int j,int[][] dirs){
            int res=1;
            grid[i][j]=0;
            for(int[] dir:dirs ){
                int x= i+dir[0];
                int y= j+dir[1];
                if(x<0 || y<0 ||x >=grid.length || y>= grid[0].length || grid[x][y]==0) continue;
                res+=dfs(grid,x,y,dirs);
            }
            return res;
        }
    }
    

Log in to reply
 

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