<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>

from collections import deque, defaultdict

class Coordinate:

    def __init__(self, x, y, grid_size):
        self._x = x
        self._y = y
        self._grid_size = grid_size
        self._flattened_coord = x * grid_size + y

    def flatten(self) -> int:
        return self._flattened_coord

    def get_next_coords(self):
        if self._x > 0:
            yield Coordinate(self._x - 1, self._y, self._grid_size)
        if self._x < self._grid_size - 1:
            yield Coordinate(self._x + 1, self._y, self._grid_size)
        if self._y > 0:
            yield Coordinate(self._x, self._y - 1, self._grid_size)
        if self._y < self._grid_size - 1:
            yield Coordinate(self._x, self._y + 1, self._grid_size)

    def get_val_at(self, grid):
        return grid[self._x][self._y]

    def set_val(self, grid, val):
        grid[self._x][self._y] = val

    def __repr__(self):
        return f"({self._x}, {self._y})"

class UnionFind:

    def __init__(self, grid_size):
        self._internal_data = {}

    def get_island_size(self, flattened_coord):
        if flattened_coord not in self._internal_data:
            return 0, flattened_coord
        while flattened_coord in self._internal_data and self._internal_data[flattened_coord] >= 0:
            flattened_coord = self._internal_data[flattened_coord]
        return -1 * self._internal_data[flattened_coord], flattened_coord

    def set_parent(self, flattened_coord, parent):
        if flattened_coord == parent:
            if parent not in self._internal_data:
                self._internal_data[parent] = -1
            return
        self._internal_data[parent] -= 1
        self._internal_data[flattened_coord] = parent

class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        potential_zero_coords = []
        grid_size = len(grid)
        connected_islands = UnionFind(grid_size)
        
        largest_island = 0
        for x in range(grid_size):
            for y in range(grid_size):
                if grid[x][y] == 0:
                    potential_zero_coords.append(Coordinate(x, y, grid_size))
                elif grid[x][y] == 1:
                    parent_coord = Coordinate(x, y, grid_size)
                    parent_coord_flattened = parent_coord.flatten()
                    grid_investigation_queue = deque()
                    grid_investigation_queue.append(parent_coord)

                    while len(grid_investigation_queue) > 0:
                        current_coord = grid_investigation_queue.popleft()
                        val_at_coord = current_coord.get_val_at(grid)
                        if val_at_coord != 1:
                            continue
                        current_coord.set_val(grid, -1)
                        connected_islands.set_parent(current_coord.flatten(), parent_coord_flattened)
                        for next_coord in current_coord.get_next_coords():
                            grid_investigation_queue.append(next_coord)
                    
                    largest_island = max(largest_island, connected_islands.get_island_size(parent_coord_flattened)[0])

        for zero_coord in potential_zero_coords:
            new_island_size = 1
            seen_islands = set()
            for adj_coord in zero_coord.get_next_coords():
                island_size, parent = connected_islands.get_island_size(adj_coord.flatten())
                if parent not in seen_islands:
                    new_island_size += island_size
                seen_islands.add(parent)
            largest_island = max(largest_island, new_island_size)
        return largest_island
71706