similar to leetcode 200, java dfs solution


  • 0
    Y
    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            if (grid == null || grid[0].length == 0)
                return 0;
            int max = 0;
            for (int i = 0; i < grid.length; i++){
                for (int j = 0 ; j < grid[0].length; j++){
                    if (grid[i][j] == 1){
                        int area = search(grid,i,j);
                        max = Math.max(area,max);
                    }
                }
            }
            return max;
        }
        public int search(int[][] grid, int m, int n){
            if (m < 0 || n < 0 || m >= grid.length || n >= grid[0].length || grid[m][n] == 0)
                return 0;
            grid[m][n] = 0;
            int left = 0, right = 0, up = 0, down = 0;
            if ((m - 1) >= 0)
                left = search(grid,m-1,n); 
            if ((m + 1) < grid.length)
                right = search(grid,m+1,n);
            if ((n - 1) >= 0)
                up = search(grid,m,n-1);
            if ((n + 1) < grid[0].length)
                down = search(grid,m,n+1);
            return 1 + left + right + up + down;    
        }
    }
    

Log in to reply
 

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