Max Area of Island
Given a 2D grid where 1 represents land and 0 represents water, find the maximum area of an island. An island is a group of connected 1s adjacent horizontally or vertically. The area is the number of 1s in the island.
For example, a grid with a 2-cell island and a 4-cell island returns 4. A grid with no land returns 0. A grid entirely filled with 1s returns the total cell count.
This problem teaches grid-based DFS/BFS traversal. It is a classic graph problem that combines component counting with area computation. Each island is a connected component in the grid graph.
The solution iterates through each cell. When land is found, perform DFS to explore the entire island, counting cells. Track the maximum area seen across all islands.
Edge cases include an empty grid (return 0), all water (return 0), a single-cell island (return 1), and the entire grid being one large island.
Example Input & Output
No land
Single cell
2x2 island
No land
Max area is 6 (the island in top-right)
Algorithm Flow
Solution Approach
Use DFS to explore each island and compute its area, tracking the maximum.
Iterate through each cell. When land (1) is found, perform DFS to compute the island's area, marking visited cells as 0 to avoid revisiting. Track the maximum area encountered. Return the maximum.
Time complexity is O(rows * cols), space complexity is O(rows * cols) worst case for the recursion stack.
Best Answers
class Solution {
int r,c;
public int solution(String[][] g) {
if(g==null||g.length==0)return 0;r=g.length;c=g[0].length;int mx=0;
for(int i=0;i<r;i++)for(int j=0;j<c;j++)if(g[i][j].equals("1"))mx=Math.max(mx,dfs(g,i,j));
return mx;
}
int dfs(String[][] g,int i,int j){
if(i<0||i>=r||j<0||j>=c||g[i][j].equals("0"))return 0;
g[i][j]="0";return 1+dfs(g,i-1,j)+dfs(g,i+1,j)+dfs(g,i,j-1)+dfs(g,i,j+1);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
