Making A Large Island - Problem
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Input & Output
Example 1 — Basic Island Connection
$
Input:
grid = [[1,0],[0,1]]
›
Output:
3
💡 Note:
Change either 0 to 1: grid becomes [[1,1],[0,1]] or [[1,0],[1,1]]. Both create an island of size 3.
Example 2 — Multiple Disconnected Islands
$
Input:
grid = [[1,1],[1,0]]
›
Output:
4
💡 Note:
Change the 0 at position (1,1) to 1. The entire grid becomes land, creating one island of size 4.
Example 3 — All Water
$
Input:
grid = [[0,0],[0,0]]
›
Output:
1
💡 Note:
Change any 0 to 1. Since no islands exist to connect, the maximum size is 1.
Constraints
- n == grid.length
- n == grid[i].length
- 1 ≤ n ≤ 500
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
Binary matrix with 1s (land) and 0s (water)
2
Find Best Position
Test each water cell to see which creates largest connected island
3
Maximum Island Size
Return the size of largest island after changing one 0 to 1
Key Takeaway
🎯 Key Insight: Pre-label islands with unique IDs to avoid recalculating sizes when testing bridge positions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code