NeetCode #563LC-695MediumGraphsNC 150NC 250
← Back to All Problems#563 · #695 · Max Area of Island(岛屿的最大面积)
📌 Problem Statement & Constraints
Given an
m x n binary matrix grid, return the maximum area of an island (1 is land, 0 is water). Return 0 if there is no island. Constraints: 1 <= m, n <= 50.💡 Core Algorithmic Approaches
- The same flood-fill as Number of Islands, but returning the area instead of counting.
- The DFS returns
1 + the areas of the four neighbours. - Mark cells visited in place to avoid double counting.
- Take the maximum over all starting cells.
💻 Benchmark Python3 Implementation
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(r: int, c: int) -> int:
if not (0 <= r < m and 0 <= c < n) or grid[r][c] != 1:
return 0
grid[r][c] = 0 # mark visited
return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1)
best = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
best = max(best, dfs(i, j))
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(m * n): each cell is visited at most once.
💾 Space Complexity
O(m * n) for the recursion stack in the worst case.
⚠️ Interview Pitfalls & Follow-ups
- Returning
max(best, 1): an empty grid must return 0. - Forgetting to mark visited before recursing: cells would be counted repeatedly (and the recursion could loop).
- Accumulating in a global counter: the DFS return value is cleaner and avoids resetting state.
- Confusing area with perimeter: the area counts cells, not edges.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.