695. Max Area of Island
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.
Example 1:
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.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 50
- grid[i][j] is either 0 or 1.
From: LeetCode
Link: 695. Max Area of Island
Solution:
Ideas:
-
dfs() recursively explores 4 directions (up, down, left, right) and counts the area.
-
We mark each visited cell by setting it to 0.
-
In maxAreaOfIsland(), we scan each cell and call dfs() whenever we find a 1.
-
We track the maximum area found.
Code:
int dfs(int** grid, int gridSize, int* gridColSize, int i, int j) {
if (i < 0 || i >= gridSize || j < 0 || j >= gridColSize[i] || grid[i][j] == 0)
return 0;
grid[i][j] = 0; // Mark as visited by setting to 0
int area = 1;
area += dfs(grid, gridSize, gridColSize, i + 1, j); // down
area += dfs(grid, gridSize, gridColSize, i - 1, j); // up
area += dfs(grid, gridSize, gridColSize, i, j + 1); // right
area += dfs(grid, gridSize, gridColSize, i, j - 1); // left
return area;
}
int maxAreaOfIsland(int** grid, int gridSize, int* gridColSize) {
int maxArea = 0;
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridColSize[i]; j++) {
if (grid[i][j] == 1) {
int area = dfs(grid, gridSize, gridColSize, i, j);
if (area > maxArea) {
maxArea = area;
}
}
}
}
return maxArea;
}