Making A Large Island - Problem
Making A Large Island
Imagine you're a landscape architect designing the perfect archipelago! You have an
An island is a group of land cells (
Key Challenge: You can only change one
Imagine you're a landscape architect designing the perfect archipelago! You have an
n Ć n grid representing a map where 1s are land and 0s are water. Your goal is to create the largest possible island by converting at most one water cell into land.An island is a group of land cells (
1s) connected horizontally or vertically (4-directional). You need to find the size of the largest island you can create after making your strategic land conversion.Key Challenge: You can only change one
0 to 1, so choose wisely! If the entire grid is already land, return n². Input & Output
example_1.py ā Basic Island Merge
$
Input:
grid = [[1,0],[0,1]]
āŗ
Output:
3
š” Note:
Changing either 0 to 1 connects the two separate islands (each of size 1) into one large island of size 3.
example_2.py ā All Land Grid
$
Input:
grid = [[1,1],[1,1]]
āŗ
Output:
4
š” Note:
The entire grid is already one large island of size 4. No changes needed.
example_3.py ā Strategic Placement
$
Input:
grid = [[1,0,0,1,0],[1,0,1,1,1],[1,0,0,1,0]]
āŗ
Output:
6
š” Note:
Changing the center water cell (1,2) to land connects multiple islands, creating the largest possible combined island.
Visualization
Tap to expand
Understanding the Visualization
1
Survey Phase
Map and label all existing islands with unique IDs
2
Catalog Phase
Record the population (size) of each island district
3
Planning Phase
For each potential bridge location, calculate total connected population
4
Optimization
Choose the bridge location that creates the largest connected region
Key Takeaway
šÆ Key Insight: Pre-labeling islands with unique IDs and caching their sizes transforms an O(nā“) problem into an O(n²) solution by eliminating redundant calculations.
Time & Space Complexity
Time Complexity
O(nā“)
O(n²) water cells à O(n²) DFS for each cell
ā Linear Growth
Space Complexity
O(n²)
DFS recursion stack and visited array
ā Quadratic Space
Constraints
- n == grid.length
- n == grid[i].length
- 1 ⤠n ⤠500
- grid[i][j] is either 0 or 1
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code