Largest Island After One Flip
Problem statement
Given a square binary matrix grid, change at most one water cell 0 into a land cell 1. An island is a group of land cells connected through shared sides; diagonals do not connect cells.
Return the largest possible island area, measured in cells, after this optional change. Keep the input unchanged. If every cell is already land, return the area of the full grid.
Function
largestIslandAfterFlip(grid: int[][]) → intExamples
Example 1
grid = [[1,0,0],[0,1,0],[0,0,1]]return = 3Changing the top-middle cell connects the top-left and center cells into an island of area 3. No water cell has all three diagonal land cells as side neighbors.
Example 2
grid = [[1,1],[0,1]]return = 4Changing the only water cell joins it to the three land cells, making area 4.
Example 3
grid = [[0]]return = 1Changing the one water cell produces one land cell, so the maximum area is 1.
Constraints
- For this exercise, assume
1 <= grid.length <= 35. - For this exercise, assume
gridis square: every row has exactlygrid.lengthentries. - Every cell is
0or1.