Max Area of Island
LeetCode 695 · Medium · solution, intuition & step-by-step walkthrough
DFS returns island size.
This is how I solved Max Area of Island (LeetCode 695), a medium problem from the Graph Fundamentals / DFS-BFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
DFS from each unvisited land cell and let it return the size of the island it explored (1 + sizes from its neighbours). Keep the largest.
Approach
- 1
For each unvisited land cell, area = dfs(cell).
- 2
dfs adds 1 plus the areas returned by unvisited land neighbours.
- 3
Track the maximum.
How I solved it
DFS areaPythonO(m·n) time
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
di = [0,+1,0,-1] #top,right,bottom,left
dj = [+1,0,-1,0] #top,right,bottom,left
m = len(grid)
n = len(grid[0])
visited = set()
def dfs(row,col):
visited.add((row,col))
max_area = 1
for k in range(4):
nrow = row+di[k]
ncol = col+dj[k]
if 0<=nrow<m and 0<=ncol<n and grid[nrow][ncol]==1 and (nrow,ncol) not in visited:
max_area+=dfs(nrow,ncol)
return max_area
max_area = 0
for row in range(m):
for col in range(n):
if grid[row][col]==1 and (row,col) not in visited:
max_area=max(max_area,dfs(row,col))
return max_areaMax Area of Island — FAQ
What is the intuition behind Max Area of Island?
DFS from each unvisited land cell and let it return the size of the island it explored (1 + sizes from its neighbours). Keep the largest.
How do you solve Max Area of Island (LeetCode 695)?
1. For each unvisited land cell, area = dfs(cell). 2. dfs adds 1 plus the areas returned by unvisited land neighbours. 3. Track the maximum.
What is the time and space complexity of Max Area of Island?
Time: O(m · n). Space: O(m · n). (Accepted approach: DFS area.)
What are common mistakes in Max Area of Island?
No land → 0.