Imagine you're an aerial photographer capturing images of a tropical archipelago! You have a binary matrix representing a satellite view where 1 represents land and 0 represents water.

Your mission: find the largest island in this beautiful archipelago. An island is a group of connected land cells (1's) that touch each other horizontally or vertically - diagonal connections don't count!

Goal: Return the area (number of cells) of the largest island. If there are no islands, return 0.

Example: In a grid like [[1,1,0],[0,1,0],[0,0,1]], we have two islands - one with area 3 (the connected group) and one with area 1, so we return 3.

Input & Output

example_1.py β€” Standard Grid
$ Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
β€Ί Output: 4
πŸ’‘ Note: There are two islands: one with area 4 (top-left) and one with area 4 (bottom-right). Both have the same area, so we return 4.
example_2.py β€” Single Cell Island
$ Input: grid = [[0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0,1,1,0,1,1,0,1,0,1,1,1,1,1,0,1,1,0,0,1,0,0,1,0]]
β€Ί Output: 6
πŸ’‘ Note: The maximum area among all islands is 6 (there's a connected group of 6 ones somewhere in the grid).
example_3.py β€” No Islands
$ Input: grid = [[0,0,0,0,0,0,0,0]]
β€Ί Output: 0
πŸ’‘ Note: There are no islands (no 1's) in the grid, so we return 0.

Visualization

Tap to expand
🏝️ Smart Island Detection Algorithm110110010000πŸ”Drone scanning...Flight pathIslands Found:Island 1: Area = 3Island 2: Area = 2Maximum Area: 3⚑ Efficient: Each cell visited exactly once using DFS
Understanding the Visualization
1
Start Survey
Begin systematic scan from top-left corner
2
Spot Land
When drone finds a '1', it starts mapping the island
3
Map Island
DFS explores all connected land, marking each cell as 'visited'
4
Count Area
Each land cell adds +1 to the island's total area
5
Continue Survey
Move to next unvisited cell and repeat until grid is complete
Key Takeaway
🎯 Key Insight: By using DFS and marking visited cells, we ensure each land cell is counted exactly once, achieving optimal O(mΓ—n) time complexity while finding the largest connected component.

Time & Space Complexity

Time Complexity
⏱️
O(m*n)

Each cell is visited exactly once during the grid traversal and DFS exploration

n
2n
βœ“ Linear Growth
Space Complexity
O(m*n)

Recursion stack can go as deep as m*n in worst case (entire grid is one island)

n
2n
⚑ Linearithmic Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≀ m, n ≀ 50
  • grid[i][j] is either 0 or 1
Asked in
Amazon 45 Facebook 38 Google 32 Microsoft 28 Apple 15
78.5K Views
High Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen