Very simple Java in-place DFS that beats on average 98.31% of Java submissions!


  • 0
    E
    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            int max = 0;
            for(int i = 0; i < grid.length; i++) {
                for(int j = 0; j < grid[0].length; j++) {
                    max = Math.max(max, dfs(i, j, grid));
                }
            }
            return max;
        }
        
        private int dfs(int i, int j, int[][] grid) {
            if(grid[i][j] == 0) return 0;
            else {
                int max = 1;
                grid[i][j] = 0;
                if(i - 1 > -1) max += dfs(i - 1, j, grid);
                if(i + 1 < grid.length) max += dfs(i + 1, j, grid);
                if(j - 1 > -1) max += dfs(i, j - 1, grid);
                if(j + 1 < grid[0].length) max += dfs(i, j + 1, grid);
                return max;
            }
        }
        
    }
    

Log in to reply
 

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