Minimum Moves to Move a Box to Their Target Location — LeetCode 1263 Python Solution

HardBreadth-First SearchArrayMatrixHeap (Priority Queue)
Problem
#1263
Reading time
7 min

The problem

A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.

Example

Input
grid = [["#","#","#","#","#","#"],
Output
3
Explanation
We return only the number of times the box is pushed.

Python solution

Python
class Solution:
    def minPushBox(self, grid: List[List[str]]) -> int:
        def f(i: int, j: int) -> int:
            return i * n + j

        def check(i: int, j: int) -> bool:
            return 0 <= i < m and 0 <= j < n and grid[i][j] != "#"

        for i, row in enumerate(grid):
            for j, c in enumerate(row):
                if c == "S":
                    si, sj = i, j
                elif c == "B":
                    bi, bj = i, j
        m, n = len(grid), len(grid[0])
        dirs = (-1, 0, 1, 0, -1)
        q = deque([(f(si, sj), f(bi, bj), 0)])
        vis = [[False] * (m * n) for _ in range(m * n)]
        vis[f(si, sj)][f(bi, bj)] = True
        while q:
            s, b, d = q.popleft()
            bi, bj = b // n, b % n
            if grid[bi][bj] == "T":
                return d
            si, sj = s // n, s % n
            for a, b in pairwise(dirs):
                sx, sy = si + a, sj + b
                if not check(sx, sy):
                    continue
                if sx == bi and sy == bj:
                    bx, by = bi + a, bj + b
                    if not check(bx, by) or vis[f(sx, sy)][f(bx, by)]:
                        continue
                    vis[f(sx, sy)][f(bx, by)] = True
                    q.append((f(sx, sy), f(bx, by), d + 1))
                elif not vis[f(sx, sy)][f(bi, bj)]:
                    vis[f(sx, sy)][f(bi, bj)] = True
                    q.appendleft((f(sx, sy), f(bi, bj), d))
        return -1

Complexity

MeasureComplexity
TimeO(m^2 \times n^2)
SpaceO(m^2 \times n^2) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1263. Minimum Moves to Move a Box to Their Target Location is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1263. Minimum Moves to Move a Box to Their Target Location?
LeetCode 1263. Minimum Moves to Move a Box to Their Target Location is rated Hard on LeetCode.
What is the time complexity of LeetCode 1263. Minimum Moves to Move a Box to Their Target Location?
The Python solution on this page runs in O(m^2 \times n^2).
What is the space complexity of LeetCode 1263. Minimum Moves to Move a Box to Their Target Location?
The Python solution on this page uses O(m^2 \times n^2) auxiliary space.
What topics does LeetCode 1263. Minimum Moves to Move a Box to Their Target Location cover?
LeetCode 1263. Minimum Moves to Move a Box to Their Target Location is tagged Breadth-First Search, Array, Matrix and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview