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

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit