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: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
n == grid.lengthn == grid[i].length1 <= n <= 500grid[i][j] is either 0 or 1.In this initial approach, the goal is to change each 0 in the grid to 1 one by one and calculate the size of the island it can form. For each conversion, we calculate the potential size of the island and keep track of the maximum size encountered. The key idea is to perform a depth-first search (DFS) to calculate the size of each connected component (island).
0, temporarily change it to a 1.0 and continue to the next 0.0 in the grid, a complete DFS traversal happens.To optimize, pre-calculate the sizes of all connected components (islands) and then analyze the potential contributions of each 0 within the grid. We use different numeric IDs for different islands and store the size corresponding to each ID. This approach reduces unnecessary recalculations.
0, check its 4 neighboring cells and sum the sizes of distinct islands formed by adjacent 1s.0 is stored as the result.