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
Making A Large Island: Connect Islands Optimally101010Original GridChange one 0→1111010After Change (0,1)→1101110After Change (1,0)→1Islands: 2 separate (size 2 each)Connected island size: 4Connected island size: 3Maximum Island Size: 4Choose the water position that connects most land
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
Asked in
Google 15 Facebook 12 Amazon 8
89.4K Views
Medium Frequency
~25 min Avg. Time
1.9K 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