<p>You are given an <code>m x n</code> binary <code>grid</code>, where each <code>1</code> represents a brick and <code>0</code> represents an empty space. A brick is <strong>stable</strong> if:</p>

<ul>
	<li>It is directly connected to the top of the grid, or</li>
	<li>At least one other brick in its four adjacent cells is <strong>stable</strong>.</li>
</ul>

<p>You are also given an array <code>hits</code>, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location <code>hits[i] = (row<sub>i</sub>, col<sub>i</sub>)</code>. The brick on that location&nbsp;(if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will <strong>fall</strong>. Once a brick falls, it is <strong>immediately</strong> erased from the <code>grid</code> (i.e., it does not land on other stable bricks).</p>

<p>Return <em>an array </em><code>result</code><em>, where each </em><code>result[i]</code><em> is the number of bricks that will <strong>fall</strong> after the </em><code>i<sup>th</sup></code><em> erasure is applied.</em></p>

<p><strong>Note</strong> that an erasure may refer to a location with no brick, and if it does, no bricks drop.</p>

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

<pre>
<strong>Input:</strong> grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
<strong>Output:</strong> [2]
<strong>Explanation: </strong>Starting with the grid:
[[1,0,0,0],
 [<u>1</u>,1,1,0]]
We erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
 [0,<u>1</u>,<u>1</u>,0]]
The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:
[[1,0,0,0],
 [0,0,0,0]]
Hence the result is [2].
</pre>

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

<pre>
<strong>Input:</strong> grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
<strong>Output:</strong> [0,0]
<strong>Explanation: </strong>Starting with the grid:
[[1,0,0,0],
 [1,<u>1</u>,0,0]]
We erase the underlined brick at (1,1), resulting in the grid:
[[1,0,0,0],
 [1,0,0,0]]
All remaining bricks are still stable, so no bricks fall. The grid remains the same:
[[1,0,0,0],
 [<u>1</u>,0,0,0]]
Next, we erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
 [0,0,0,0]]
Once again, all remaining bricks are still stable, so no bricks fall.
Hence the result is [0,0].
</pre>

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

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 200</code></li>
	<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
	<li><code>1 &lt;= hits.length &lt;= 4 * 10<sup>4</sup></code></li>
	<li><code>hits[i].length == 2</code></li>
	<li><code>0 &lt;= x<sub>i&nbsp;</sub>&lt;= m - 1</code></li>
	<li><code>0 &lt;=&nbsp;y<sub>i</sub> &lt;= n - 1</code></li>
	<li>All <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are unique.</li>
</ul>

from copy import deepcopy


class Solution:
    def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:
        dummy_grid = deepcopy(grid)
        for hit in hits:
            dummy_grid[hit[0]][hit[1]] = 0
        res = []
        uf = UnionFind(dummy_grid)
        uf.build()
        num_valid_bricks = uf.cluster[-1]
        # we cannot use hits[n - 1: -1: -1] !!! This is different from range() usage
        for hit in hits[len(hits) - 1 :: -1]:
            x = hit[0]
            y = hit[1]
            # we need to ensure the original grid[x][y] == 1
            if grid[x][y] == 1:
                dummy_grid[x][y] = 1
                uf.add(tuple(hit))
                for d in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                    nx = x + d[0]
                    ny = y + d[1]
                    if (
                        nx >= 0
                        and ny >= 0
                        and nx < len(grid)
                        and ny < len(grid[0])
                        and dummy_grid[nx][ny] == 1
                    ):
                        uf.union((x, y), (nx, ny))
                res.append(
                    uf.cluster[-1] - num_valid_bricks - 1
                    if uf.cluster[-1] > num_valid_bricks
                    else 0
                )
                num_valid_bricks = uf.cluster[-1]
            else:
                res.append(0)
        return res[::-1]


class UnionFind:
    def __init__(self, dummy_grid: List[List[int]]) -> None:
        self.parent = {}
        self.cluster = defaultdict(int)
        self.grid = dummy_grid
        self.m = len(dummy_grid)
        self.n = len(dummy_grid[0])

        self.parent[-1] = -1
        for i in range(self.m):
            for j in range(self.n):
                k = i * self.n + j
                if dummy_grid[i][j] == 1:
                    parent_k = -1 if i == 0 else k
                    self.parent[k] = parent_k
                    self.cluster[parent_k] = self.cluster[parent_k] + 1

    def union(self, a: tuple[int, int], b: tuple[int, int]) -> None:
        k_a = a[0] * self.n + a[1]
        k_b = b[0] * self.n + b[1]
        p_a = self.find(k_a)
        p_b = self.find(k_b)
        # avoid duplicated update if two nodes already in the same cluster
        if p_a == p_b:
            return None
        if p_a == -1:
            self.parent[p_b] = p_a
            self.cluster[-1] += self.cluster[p_b]
        else:
            self.parent[p_a] = p_b
            self.cluster[p_b] += self.cluster[p_a]

    def find(self, k) -> int:
        if self.parent[k] != k:
            self.parent[k] = self.find(self.parent[k])
        return self.parent[k]

    def add(self, a: tuple[int, int]) -> None:
        k = a[0] * self.n + a[1]
        parent_k = -1 if a[0] == 0 else k
        self.parent[k] = parent_k
        self.cluster[parent_k] = self.cluster[parent_k] + 1

    def build(self) -> None:
        for x in range(len(self.grid)):
            for y in range(len(self.grid[0])):
                if self.grid[x][y] == 1:
                    for d in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                        nx = x + d[0]
                        ny = y + d[1]
                        if (
                            nx >= 0
                            and ny >= 0
                            and nx < len(self.grid)
                            and ny < len(self.grid[0])
                            and self.grid[nx][ny] == 1
                        ):
                            self.union((x, y), (nx, ny))

27800