You can change at most one 0 to 1.
The naive trap is re-flooding for every zero in O((mn)²).
The optimal O(mn) way: Pass 1 labels each component with a unique ID and maps its area.
Pass 2 tests flipping each 0 by summing distinct adjacent IDs via a Set.
"Do not re-flood for every zero. Flipping each zero and running DFS traverses overlapping islands repeatedly, resulting in an unacceptable $O((m \cdot n)^2)$ time."
"In Pass 1, we run DFS on untouched 1s, tagging all cells in that island with a unique ID ($\ge 2$ to avoid colliding with 0 and 1). We record sizeMap[islandId] = size in $O(m \cdot n)$ time."
"In Pass 2, for each 0, we inspect its 4 neighbors. We insert neighbor IDs into a Set<Integer> to avoid double-counting if two sides touch the same island! Potential area = $1 + \sum_{\text{id} \in \text{seen}} \text{sizeMap}[\text{id}]$."
"If the grid has no zeros, return $m \cdot n$. If the grid has no ones, flipping any zero produces 1. Total time and space are both optimal $O(m \cdot n)$."