Untitled

 avatar
unknown
java
3 years ago
1.4 kB
2
Indexable
class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        
        //whichever land block we visit, we will multiply it by 10 after our calclulations
        //this way we can avoid repeated calculations of area for same island
        
        int max = 0;
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                if (grid[r][c] == 1) {
                    int currArea = 0;
                    currArea = addArea(grid, r, c, currArea);
                    max = Math.max(max, currArea);
                }
            }
        }
        
        return max;
    }
    
    public int addArea(int[][] grid, int r, int c, int currArea) {
        
        int isLand = grid[r][c];
        grid[r][c] = grid[r][c]*2;
        if (grid[r][c] == 1) {
            
            currArea++;
            if (r - 1 >= 0) {
                addArea(grid, r - 1, c, currArea);
            }
            if (c - 1 >= 0) {
                addArea(grid, r, c - 1, currArea);
            }
            if (r + 1 < grid.length) {
                addArea(grid, r + 1, c, currArea);
            }
            if (c + 1 < grid[0].length) {
                addArea(grid, r, c + 1, currArea);
            }
        }
        
        return currArea;
        
    }
}