Max Area of Island (LeetCode 695): Solution and Explanation
A grid of 0s and 1s marks water and land. Land cells that touch up, down, left or right belong to the same island. Return the number of cells in the largest island, or 0 if there is no land at all.
Watch it run step by step
Try your own input and write the code →Intuition
This is the counting version of the classic island problem. Instead of asking how many islands exist, it asks how big the biggest one is, but the structure of the solution is the same: treat the grid as a graph where each land cell connects to its land neighbors, and find connected components.
A naive approach might try to compute, for every land cell, the size of the island it belongs to. That repeats the same flood fill many times over, once per cell in each island, and on a grid that is all land it becomes quadratic in the number of cells.
The fix is to explore each island exactly once. Scan the grid, and whenever you hit a land cell that has not been explored, launch a depth-first search from it. The DFS returns how many cells it reached: each call counts its own cell as 1 and adds whatever its four neighbors return. Out-of-bounds positions and water return 0, which keeps the recursion simple.
To guarantee that no cell is counted twice, the DFS sinks every cell it visits by setting it to 0 before exploring the neighbors. That doubles as the visited set, so no extra memory is needed, and it means later scan positions inside the same island are skipped automatically. The answer is the largest area any DFS returns.
Approach: DFS flood fill with in-place marking
- Return 0 for an empty grid, and record
rows,colsandmax_area = 0. - Define
dfs(r, c)that returns 0 if the position is out of bounds orgrid[r][c] == 0. - Otherwise set
grid[r][c] = 0to mark it visited, and startareaat 1 for this cell. - Add the results of
dfson the four neighbors (down, up, right, left) toareaand return it. - Scan every cell, and when
grid[r][c] == 1, updatemax_areawith the area returned bydfs(r, c). - Return
max_areaafter the scan.
Step-by-step example
grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,1]]
- The scan reaches (0,0), which is land, so a DFS begins there and sinks it.
- From (0,0) the DFS goes down to (1,0), which is land and has no further land neighbors, so it returns 1. Going right reaches (0,1), which also returns 1. The DFS at (0,0) returns 1 + 1 + 1 = 3, and
max_areabecomes 3. - The scan passes (0,1) and (1,0), which are now 0, and reaches (1,3), the next land cell.
- From (1,3) the DFS goes down to (2,3). From there it goes down to (3,3), worth 1, and left to (2,2), worth 1. So (2,3) returns 3 and (1,3) returns 4.
max_areabecomes 4. Every remaining cell is water, so the answer is 4.
Code: Python, Java, C++
1class Solution:
2 def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
3 if not grid:
4 return 0
5
6 rows, cols = len(grid), len(grid[0])
7 max_area = 0
8
9 def dfs(r, c):
10 if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:
11 return 0
12 grid[r][c] = 0 # Mark as visited
13 area = 1
14 area += dfs(r + 1, c)
15 area += dfs(r - 1, c)
16 area += dfs(r, c + 1)
17 area += dfs(r, c - 1)
18 return area
19
20 for r in range(rows):
21 for c in range(cols):
22 if grid[r][c] == 1:
23 max_area = max(max_area, dfs(r, c))
24
25 return max_area1class Solution {
2 public int maxAreaOfIsland(int[][] grid) {
3 if (grid == null || grid.length == 0) return 0;
4
5 int rows = grid.length;
6 int cols = grid[0].length;
7 int maxArea = 0;
8
9 for (int r = 0; r < rows; r++) {
10 for (int c = 0; c < cols; c++) {
11 if (grid[r][c] == 1) {
12 maxArea = Math.max(maxArea, dfs(grid, r, c));
13 }
14 }
15 }
16
17 return maxArea;
18 }
19
20 private int dfs(int[][] grid, int r, int c) {
21 if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0) {
22 return 0;
23 }
24 grid[r][c] = 0; // Mark as visited
25 int area = 1;
26 area += dfs(grid, r + 1, c);
27 area += dfs(grid, r - 1, c);
28 area += dfs(grid, r, c + 1);
29 area += dfs(grid, r, c - 1);
30 return area;
31 }
32}1class Solution {
2public:
3 int maxAreaOfIsland(vector<vector<int>>& grid) {
4 if (grid.empty()) return 0;
5
6 int rows = grid.size();
7 int cols = grid[0].size();
8 int maxArea = 0;
9
10 for (int r = 0; r < rows; r++) {
11 for (int c = 0; c < cols; c++) {
12 if (grid[r][c] == 1) {
13 maxArea = max(maxArea, dfs(grid, r, c));
14 }
15 }
16 }
17
18 return maxArea;
19 }
20
21private:
22 int dfs(vector<vector<int>>& grid, int r, int c) {
23 if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] == 0) {
24 return 0;
25 }
26 grid[r][c] = 0; // Mark as visited
27 int area = 1;
28 area += dfs(grid, r + 1, c);
29 area += dfs(grid, r - 1, c);
30 area += dfs(grid, r, c + 1);
31 area += dfs(grid, r, c - 1);
32 return area;
33 }
34};Time and space complexity
O(m × n)
The scan touches every cell once, and each land cell is sunk and expanded by exactly one DFS call. Each call does constant work besides its four neighbor checks, so the total is proportional to the number of cells.
O(m × n)
Marking happens in place, but the recursion can go as deep as the size of the largest island, which is all m × n cells for a grid full of land.
Other approaches
BFS with a queue (time O(m × n), space O(min(m, n)))
Replace the recursion with a queue: push the starting cell, mark it, and count cells as you pop them while pushing unvisited land neighbors. It avoids recursion depth limits in Python on large grids, and its queue only holds the frontier.
Union-find (time O(m × n × α(m × n)), space O(m × n))
Union each land cell with its land neighbors and track the size of each set. The largest set size is the answer. It is overkill here but useful when land cells arrive over time.
Common mistakes
- Marking the cell visited after exploring the neighbors instead of before. Two neighbors then recurse into each other forever, or cells get counted twice.
- Counting islands rather than measuring them, for example adding 1 per DFS launch instead of using the returned area.
- Hitting Python's recursion limit on large all-land grids. Raise the limit or switch to an iterative stack or BFS when the grid can be big.
- Including diagonal neighbors. Only the four orthogonal directions connect land in this problem.
Frequently asked questions
What is the time complexity of Max Area of Island?
O(m × n). Every cell is looked at by the outer scan, and every land cell is visited by exactly one DFS, because it is set to 0 the first time it is reached.
Can I avoid modifying the input grid?
Yes. Use a separate visited set or boolean matrix instead of overwriting cells with 0. It costs O(m × n) extra memory but leaves the input intact.
BFS or DFS for Max Area of Island?
Both have the same time complexity. DFS is the shortest to write, while BFS or an explicit stack avoids deep recursion, which matters in Python on large grids.