MEDIUM NC#82 Graphs / DFS
695. Max Area of Island
๐ Problem
You are given an m x n binary matrix grid where 0 represents water and 1 represents land. Find the maximum area of an island in grid. The island is connected by 4-directionally (horizontal or vertical) land cells.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขRecursive stack flow
- โขCycle prevention
- โขPost-order reasoning
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply DFS reasoning pattern
- โขApply Recursion reasoning pattern
๐ก Approach
- โ Use DFS to explore each island
- โ Track visited cells to avoid revisiting
- โ Calculate area for each cell (current * future islands)
- โ Keep track of maximum area seen
- โ Time: O(m * n), Space: O(m * n) for recursion
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse DFS to explore each island
- โขTrack visited cells to avoid revisiting
- โขCalculate area for each cell (current * future islands)
Common Pitfalls
- โขKeep track of maximum area seen
- โขTime: O(m * n), Space: O(m * n) for recursion
๐งช Test Cases
Hidden tests on submit: 3
Test Case 1
Not run Input:
dfs(i, j, i + 1, 0); Expected:
Computed from hidden reference Test Case 2
Not run Input:
dfs(r: number, c: number, newColor: number); Expected:
Computed from hidden reference Test Case 3
Not run Input:
dfs(r - 1, c, newColor); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output