695. Max Area of Island
Description
You are given an m x n
binary matrix grid
. An island is a group of 1
's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1
in the island.
Return the maximum area of an island in grid
. If there is no island, return 0
.
Constraints
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either0
or1
.
Approach
Links
Binarysearch
GeeksforGeeks
ProgramCreek
YouTube
Examples
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.

Solutions
/**
* Time complexity : O(R*C), where R is the number of rows in the given grid,
* and C is the number of columns. We visit every square once.
* Space complexity : O(R*C), the space used by seen to keep track of
* visited squares, and the space used by stack.
*/
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
if(grid != null && grid.length != 0) {
int rows = grid.length, cols = grid[0].length;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(grid[i][j] == 1) {
maxArea = Math.max(maxArea, calcArea(grid, i, j));
}
}
}
}
return maxArea;
}
private int calcArea(int[][] grid, int x, int y) {
if(x < 0 || x >= grid.length ||
y < 0 || y >= grid[0].length || grid[x][y] != 1) {
return 0;
}
grid[x][y] = 2;
return 1 + calcArea(grid, x-1, y) + calcArea(grid, x, y+1) +
calcArea(grid, x+1, y) + calcArea(grid, x, y-1);
}
}
Follow up
Last updated
Was this helpful?