<p>You are given an <code>n x n</code> binary matrix <code>grid</code>. You are allowed to change <strong>at most one</strong> <code>0</code> to be <code>1</code>.</p>

<p>Return <em>the size of the largest <strong>island</strong> in</em> <code>grid</code> <em>after applying this operation</em>.</p>

<p>An <strong>island</strong> is a 4-directionally connected group of <code>1</code>s.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,0],[0,1]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,1],[1,0]]
<strong>Output:</strong> 4
<strong>Explanation: </strong>Change the 0 to 1 and make the island bigger, only one island with area = 4.</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,1],[1,1]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Can&#39;t change any 0 to 1, only one island with area = 4.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= n &lt;= 500</code></li>
	<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>

# https://leetcode.com/problems/making-a-large-island/
# https://leetcode.com/problems/number-of-islands-ii/

class UnionFind:
    def __init__(self, n: int) -> None:
        self.par = {i:i for i in range(n)}
        # 需要额外维护每个根节点的大小
        self.sz = {i:1 for i in range(n)}
    
    def find(self, n: int) -> int:
        if self.par[n] != n:
            self.par[n] = self.find(self.par[n])
        return self.par[n]
    
    def union(self, n1: int, n2: int) -> bool:
        r1, r2 = self.find(n1), self.find(n2)
        if r1 == r2:
            return False
        self.par[r1] = r2
        # 挂载时，parent 的节点数量需要增加被挂在的节点数量
        self.sz[r2] += self.sz[r1]
        return True


class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        M, N = len(grid), len(grid[0])
        uf = UnionFind(M * N)
        visited = set()

        def bfs(r: int, c: int) -> None:
            # visited.add((r, c))
            q = deque([(r, c)])

            while q:
                r, c = q.popleft()
                # 易错点：idx 的取值是乘以 N 不是 M
                idx1 = r * N + c
                # 关键点：只需要向前方尝试合并即可，不用向反方向尝试合并
                for x, y in ((r + 1, c), (r, c + 1)):
                    if 0 <= x < M and 0 <= y < N and grid[x][y] == 1:
                        # visited.add((x, y))
                        # 易错点：idx 的取值是乘以 N 不是 M
                        idx2 = x * N + y
                        # 尝试合并，无需在意返回值是 True/False
                        uf.union(idx1, idx2)

        def cal(r: int, c: int) -> int:
            roots = set()
            for x, y in ((r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)):
                if 0 <= x < M and 0 <= y < N and grid[x][y] == 1:
                    idx = x * N + y
                    # 易错点：此时只需要寻找根，不需要 union 合并
                    roots.add(uf.find(idx))

            # ans 初始化为 1 代表将当前海洋填为陆地
            ans = 1
            for root in roots:
                ans += uf.sz[root]
            return ans

        # 核心逻辑：合并联通分量并记录各个联通分量的 size
        for i in range(M):
            for j in range(N):
                # 易错点：此时遍历陆地
                if grid[i][j] == 1:
                    bfs(i, j)

        # 核心逻辑：尝试合并联通分量，并计算合并后的最大面积
        res = max(uf.sz.values())
        for i in range(M):
            for j in range(N):
                # 易错点：此时遍历海洋
                if grid[i][j] == 0:
                    res = max(res, cal(i, j))
        return res

68143