Sunday, September 15, 2019

695. max-area-of-island

695. max-area-of-island
  • 방문한 곳은 1 to 2로 치환하고 연결된 모든 섬의 count를 구해서 max sum을 구한다.
Runtime: 2 ms, faster than 100.00% of Java online submissions for Max Area of Island.
Memory Usage: 43.6 MB, less than 55.56% of Java online submissions for Max Area of Island.
public class Solution {
    int maxSum =0;
    public  int maxAreaOfIsland(int[][] grid) {
        if(grid.length ==0){
            return 0;
        }

        for(int i=0; i<grid.length; i++){
            for(int j=0; j<grid[0].length; j++){
                if(grid[i][j] == 1){
                    int sum = visit(i, j, grid);
                    maxSum = Math.max(maxSum, sum);
                }
            }
        }
        return maxSum;
    }

    private int visit(int i, int j, int[][] grid) {
        int sum=0;
        if(i >=0 && i<grid.length && j>=0 && j<grid[i].length){
            if(grid[i][j] ==1){
                sum++;
                grid[i][j] =2;
                sum+=visit(i+1, j, grid);
                sum+=visit(i-1, j, grid);
                sum+=visit(i, j-1, grid);
                sum+=visit(i, j+1, grid);
            }
        }
        return sum;
    }
}

No comments:

Post a Comment