DSA Graphs

Max Area of Island

DFS each unvisited land cell; flood-fill, count cells, track the maximum.

Medium
Time O(m*n) Space O(m*n)
LeetCode
4 min read
dfs grid flood-fill

Problem#

Given a binary grid, return the maximum area of any island (connected group of 1s by 4-direction adjacency). Return 0 if none.

Examples#

  • [[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],...]6
  • [[0,0,0,0,0,0,0,0]]0

Constraints#

  • m == grid.length, n == grid[i].length, 1 <= m, n <= 50.

Approach#

Scan each cell. On finding grid[i][j] == 1, run a DFS that flips visited cells to 0 and counts them.

Solution#

Max Area of Island
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), best = 0;
function<int(int,int)> dfs = [&](int r, int c) -> int {
if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 0) return 0;
grid[r][c] = 0;
return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1);
};
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1) best = max(best, dfs(i, j));
return best;
}
};

Editorial#

Marking visited by mutating to 0 saves on a separate visited matrix. Each cell is visited at most once, so the overall sweep is O(m*n). Recursion depth is bounded by the largest island area.

Complexity#

  • Time: O(m*n).
  • Space: O(m*n) recursion in the worst case.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.