dfs solution using java!


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

Log in to reply
 

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