jzhangnu / Leetcode-JS-Solutions

:tropical_drink: Leetcode solutions using JavaScript.
52 stars 7 forks source link

695. Max Area of Island #128

Open jzhangnu opened 6 years ago

jzhangnu commented 6 years ago
var maxAreaOfIsland = function(grid) {
  var maxArea = 0;
  for (var i = 0; i < grid.length; i++){
    for (var j = 0; j < grid[0].length; j++){
      if (grid[i][j] != 0){
        maxArea = Math.max(maxArea, area(grid, i, j));
      }
    }
  }

    return maxArea;
};

function area(grid, i, j){
  if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] != 0){
    grid[i][j] = 0;
    return 1 + area(grid,i+1,j) + area(grid,i-1,j) + area(grid,i,j+1) + area(grid,i,j-1);
  }
  return 0;
}