Minimum Moves to Move a Box to Their Target Location Problem
Description
LeetCode Problem 1263.
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.
Your task is to move the box 'B' to the target position 'T' under the following rules:
- The character
'S'represents the player. The player can move up, down, left, right ingridif it is a floor (empty cell). - The character
'.'represents the floor which means a free cell to walk. - The character
'#'represents the wall which means an obstacle (impossible to walk there). - There is only one box
'B'and one target cell'T'in thegrid. - 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 push.
- The player cannot walk through the box.
Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.
Example 1:

Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#",".","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 3
Explanation: We return only the number of times the box is pushed.
Example 2:
Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#","#","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: -1
Example 3:
Input: grid = [["#","#","#","#","#","#"],
["#","T",".",".","#","#"],
["#",".","#","B",".","#"],
["#",".",".",".",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 5
Explanation: push the box down, left, left, up and up.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 20gridcontains only characters'.','#','S','T', or'B'.- There is only one character
'S','B', and'T'in thegrid.
Solution
Approach: BFS over (Player, Box) States, One Level per Push
The box only moves when the player pushes it, and where the player can stand depends on where the box is. So the state of the game is the pair (player cell, box cell). From a state the player steps to one of the four neighboring cells:
- If that cell is free (not a wall, inside the grid, and not the box), the player just walks. This costs 0 pushes.
- If that cell is the box, the player pushes it one cell further in the same direction, provided that cell is free. The player takes the box's old cell. This costs 1 push.
We want the fewest pushes, not the fewest steps, so a plain BFS that counts every step would be wrong. Instead we search level by level: level d holds all states reachable with exactly d pushes. Within a level, walking moves add states to the same level's queue, and pushes go to the next level's list. A state is marked as seen when it is taken into a level's queue, not when a push first produces it. That way a state that can also be reached by walking in the current level is processed there, with the smaller push count. As soon as we take a state whose box is on T, the current level number is the answer. If the levels run out, the box can never reach T, so we return -1.
There are at most (m·n)2 = 160,000 states, so we encode a state as player × (m·n) + box and keep a flat seen array.
Complexity: O(m2·n2) time and space, since each state is processed at most once and has four moves.
class Solution:
def minPushBox(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
mn = m * n
for i in range(m):
for j in range(n):
if grid[i][j] == "S":
player = i * n + j
elif grid[i][j] == "B":
box = i * n + j
elif grid[i][j] == "T":
target = i * n + j
def free(r: int, c: int) -> bool:
return 0 <= r < m and 0 <= c < n and grid[r][c] != "#"
# A state is (player cell, box cell), stored as player * mn + box. Walking costs nothing and a
# push costs 1, so we search level by level: level d holds the states reached with d pushes.
seen = bytearray(mn * mn)
level = [player * mn + box]
pushes = 0
while level:
queue = []
for s in level:
if not seen[s]:
seen[s] = 1
queue.append(s)
next_level = []
i = 0
while i < len(queue): # walking adds states to this same level
p, b = divmod(queue[i], mn)
i += 1
if b == target:
return pushes
pr, pc = divmod(p, n)
br, bc = divmod(b, n)
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
r, c = pr + dr, pc + dc
if not free(r, c):
continue
if r * n + c == b:
# Stepping into the box pushes it one cell the same way.
if free(br + dr, bc + dc):
next_level.append(b * mn + (br + dr) * n + bc + dc)
elif not seen[(r * n + c) * mn + b]:
seen[(r * n + c) * mn + b] = 1
queue.append((r * n + c) * mn + b)
level = next_level
pushes += 1
return -1