<p>A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.</p>

<p>The game is represented by an <code>m x n</code> grid of characters <code>grid</code> where each element is a wall, floor, or box.</p>

<p>Your task is to move the box <code>&#39;B&#39;</code> to the target position <code>&#39;T&#39;</code> under the following rules:</p>

<ul>
	<li>The character <code>&#39;S&#39;</code> represents the player. The player can move up, down, left, right in <code>grid</code> if it is a floor (empty cell).</li>
	<li>The character <code>&#39;.&#39;</code> represents the floor which means a free cell to walk.</li>
	<li>The character<font face="monospace">&nbsp;</font><code>&#39;#&#39;</code><font face="monospace">&nbsp;</font>represents the wall which means an obstacle (impossible to walk there).</li>
	<li>There is only one box <code>&#39;B&#39;</code> and one target cell <code>&#39;T&#39;</code> in the <code>grid</code>.</li>
	<li>The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a <strong>push</strong>.</li>
	<li>The player cannot walk through the box.</li>
</ul>

<p>Return <em>the minimum number of <strong>pushes</strong> to move the box to the target</em>. If there is no way to reach the target, return <code>-1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2019/11/06/sample_1_1620.png" style="width: 500px; height: 335px;" />
<pre>
<strong>Input:</strong> grid = [[&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;T&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;.&quot;,&quot;B&quot;,&quot;.&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;#&quot;,&quot;#&quot;,&quot;.&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;S&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We return only the number of times the box is pushed.</pre>

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

<pre>
<strong>Input:</strong> grid = [[&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;T&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;.&quot;,&quot;B&quot;,&quot;.&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;.&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;S&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;]]
<strong>Output:</strong> -1
</pre>

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

<pre>
<strong>Input:</strong> grid = [[&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;T&quot;,&quot;.&quot;,&quot;.&quot;,&quot;#&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;#&quot;,&quot;B&quot;,&quot;.&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;S&quot;,&quot;#&quot;],
               [&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;]]
<strong>Output:</strong> 5
<strong>Explanation:</strong> push the box down, left, left, up and up.
</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;= 20</code></li>
	<li><code>grid</code> contains only characters <code>&#39;.&#39;</code>, <code>&#39;#&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;T&#39;</code>, or <code>&#39;B&#39;</code>.</li>
	<li>There is only one character <code>&#39;S&#39;</code>, <code>&#39;B&#39;</code>, and <code>&#39;T&#39;</code> in the <code>grid</code>.</li>
</ul>

import time

class Solution:
    def minPushBox(self, grid: List[List[str]]) -> int:
        m = len(grid)
        n = len(grid[0])
        drs = [(0, -1), (0, 1), (-1, 0), (1, 0)]

        def dump(gd: List[List[str]], summary: str, **kwargs: Dict[str, Tuple[int, int]]):
            print(summary)
            for k, v in kwargs.items():
                gd[v[0]][v[1]] = k
            print('\n'.join([''.join(it) for it in gd]))

        def find(gd: List[List[str]], a: List[str]) -> Dict[str, Tuple[int, int]]:
            ps = dict()
            for r in range(m):
                for c in range(n):
                    x = gd[r][c]
                    if x in a:
                        ps[x] = (r, c)
            return ps

        def dots(gd: List[List[str]], a: List[str]):
            for r in range(m):
                for c in range(n):
                    if gd[r][c] in a:
                        gd[r][c] = "."

        def fill(gd: List[List[str]], a: Tuple[int, int], b: str):
            pq, nx = set([a]), set([])
            while pq:
                nx.clear()
                for r, c in pq:
                    gd[r][c] = b
                    for ri, rc in drs:
                        x = r + ri
                        y = c + rc
                        if 0 <= x < m and 0 <= y < n and gd[x][y] == '.':
                            nx.add((x, y))
                pq, nx = nx, pq

        def solve(gd: List[List[str]]) -> int:
            # dump(gd, "---")
            ps = find(gd, ("T", "B", "S"))
            t, b, s = ps["T"], ps["B"], ps["S"]
            # print(f"{t=} {b=} {s=}")
            dots(gd, "TBS")

            fill(gd, s, "-")
            # dump(gd, "connects") #, T=t, B=b, S=s
            if gd[t[0]][t[1]] != "-" or gd[b[0]][b[1]] != "-":
                return -1
            dots(gd, "-TBS")

            pq, nx = set([(b, s)]), set([])
            ans = -1

            # start = time.time()
            vt = set()
            while pq and ans < 50:
                # elapsed = round(time.time() - start, 3)
                ans += 1
                nx.clear()
                # for it in pq:
                #     gd[it[0][0]][it[0][1]] = "x"
                # dump(gd, f"{ans=} {elapsed=} {len(pq)=} {pq=}")
                # dots(gd, "x")
                for it in pq:
                    vt.add(it)
                    b, s = it
                    if b == t:
                        return ans

                    gd[b[0]][b[1]] = "B"
                    fill(gd, s, "-")
                    # dump(gd, f"{b=} {s=}")

                    for r, c in drs:
                        x1 = b[0] + r
                        y1 = b[1] + c
                        q1 = 0 <= x1 < m and 0 <= y1 < n and gd[x1][y1] in ("-", ".")
                        x2 = b[0] - r
                        y2 = b[1] - c
                        q2 = 0 <= x2 < m and 0 <= y2 < n and gd[x2][y2] == "-"
                        # print(f"{b=} {(x1, y1, q1)=} {(x2, y2, q2)=}")
                        if q1 and q2:
                            pt = ((x1, y1), b)
                            if pt not in vt:
                                nx.add(pt)

                    # dump(gd, f"{b=} {s=} {nx=}", T=t, B=b, S=s)
                    dots(gd, "-B")

                pq, nx = nx, pq

            return -1

        return solve(grid)

299