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 INPUT Binary Matrix (2x2) 1 0 0 1 [0,0] [0,1] [1,0] [1,1] grid = [[1,0],[0,1]] Two separate islands = Land (1) = Water (0) ALGORITHM STEPS 1 Label Islands with DFS Assign unique ID to each island 2 0 0 3 2 Store Island Sizes Map: {2: 1, 3: 1} 3 Try Each Zero Check neighbors for islands 4 Calculate Max Size Sum unique neighbor islands Flip [0,1] or [1,0]: 1 (flipped) + 1 (island 2) + 1 (island 3) = 3 Connects both islands! FINAL RESULT After flipping [0,1] to 1: 1 1 FLIP 0 1 Connected Island Size: 3 Output: 3 Largest possible island OK - DONE Key Insight: Use DFS to label each island with unique ID and store sizes in a hashmap. Then for each 0 cell, check 4 neighbors and sum sizes of unique adjacent islands + 1 (the flipped cell). This avoids counting the same island twice when it borders the 0 from multiple sides. Time: O(n^2) TutorialsPoint - Making A Large Island | Island Labeling with DFS
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