Python 1263.py
class Solution:
def minPushBox(self, grid: List[List[str]]) -> int:
height = len(grid)
width = len(grid[0])
# compact representation of four directions
deltas = ( 0, +1, 0, -1, 0 )
# player
px = py = 0
# box
bx = by = 0
# target
tx = ty = 0
# alls cells within bounds and not being a wall
valid = set()
# locate these three points
for y in range(height):
for x in range(width):
cell = grid[y][x]
if cell == "S":
px = x
py = y
elif cell == "B":
bx = x
by = y
elif cell == "T":
tx = x
ty = y
if cell != "#":
valid.add(( x, y ))
seen = set() # avoid loops
todo = set([ ( px, py, bx, by ) ]) # position of player and box
next = set() # push once more
push = 0 # number of pushes in "todo" (push + 1 in "next")
while todo or next:
# need one more push
if not todo:
todo = next
next = set()
push += 1
px, py, bx, by = todo.pop()
# move player
for dx, dy in zip(deltas, deltas[1 :]):
x = px + dx
y = py + dy
# check walls / out-of-bounds
if (x, y) not in valid:
continue
if x == bx and y == by:
# push box
bbxx = bx + dx
bbyy = by + dy
# done
if bbxx == tx and bbyy == ty:
return push + 1
# move box only if cell is free
id = ( x, y, bbxx, bbyy )
if ( bbxx, bbyy ) in valid and id not in seen:
next.add(id)
else:
# just move player
id = ( x, y, bx, by )
if id not in seen:
todo.add(id)
seen.add(id)
# failed
return -1
Difficulty
and has an acceptance rate of about 50% (60k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Heap (Priority Queue)
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The minPushBox method computes the smallest number of pushes required to move a box (B) onto a target cell (T) in a rectangular grid. The grid contains empty cells, walls (#), the player start position (S), the box, and the target. The algorithm explores reachable configurations of player and box positions using a breadth-first search (BFS) that expands one push at a time.
Initialization and Grid Parsing
The function first records the dimensions of the grid and creates a compact representation of the four cardinal directions. It then scans every cell to locate the player, the box, and the target while building a set of all traversable cells (those that are not walls).
height = len(grid)
width = len(grid[0])
deltas = (0, +1, 0, -1, 0)
px = py = 0 # player coordinates
bx = by = 0 # box coordinates
tx = ty = 0 # target coordinates
valid = set() # cells that are inside the grid and not a wall
for y in range(height):
for x in range(width):
cell = grid[y][x]
if cell == "S":
px, py = x, y
elif cell == "B":
bx, by = x, y
elif cell == "T":
tx, ty = x, y
if cell != "#":
valid.add((x, y))
The valid set enables constant-time checks for walls and out-of-bounds moves.
State Representation and Search Structures
Each search state is a 4-tuple (player_x, player_y, box_x, box_y). Two sets, todo and next, hold states that are reachable with the current number of pushes and with one additional push, respectively. The seen set records every state that has ever been generated, preventing revisits. The integer push counts how many pushes have been performed to reach the states in todo.
seen = set()
todo = set([(px, py, bx, by)]) # states reachable without any push
next = set()
push = 0
Main BFS Loop
The outer while loop continues until both todo and next are empty, meaning all reachable configurations have been examined. When todo becomes empty, the algorithm swaps next into todo, clears next, and increments the push counter, thereby moving to the next BFS layer.
while todo or next:
if not todo:
todo, next = next, set()
push += 1
px, py, bx, by = todo.pop()
...
This layered approach guarantees that the first time the target is reached corresponds to the minimal number of pushes.
Player Movement and Box Push Logic
For each extracted state, the algorithm iterates over the four directions using the deltas tuple. It computes the adjacent cell for the player and checks whether that cell is traversable. Two cases arise:
-
Simple move - the adjacent cell is free and does not contain the box. The player can walk there without affecting the push count. The new state is added to
todoif it has not been seen before. -
Box push - the adjacent cell holds the box. The algorithm then checks whether the cell beyond the box is free. If it is, the box is moved one step in the same direction, the player occupies the box’s former cell, and the new configuration is placed into
next(one more push). If the box lands on the target, the function returns the total pushes required.
for dx, dy in zip(deltas, deltas[1:]):
x = px + dx
y = py + dy
if (x, y) not in valid:
continue
if x == bx and y == by: # player tries to push the box
bbxx = bx + dx
bbyy = by + dy
if bbxx == tx and bbyy == ty: # box reaches target
return push + 1
if (bbxx, bbyy) in valid:
id = (x, y, bbxx, bbyy)
if id not in seen:
next.add(id)
else: # ordinary player move
id = (x, y, bx, by)
if id not in seen:
todo.add(id)
seen.add(id)
The seen set is updated for ordinary moves immediately, ensuring that the same configuration is never queued again, while push states are added to next without immediate insertion into seen; they will be marked when they become part of todo in the next layer.
Goal Detection
The algorithm detects success precisely when the box’s next position after a push coincides with the target coordinates. At that moment it returns push + 1, accounting for the current push that just placed the box on the target.
Edge Cases Handled
The code gracefully handles several boundary conditions:
- Cells that are walls or lie outside the grid are excluded by the
validset, preventing illegal moves. - Situations where the player is adjacent to the box but the cell behind the box is a wall or out of bounds are ignored because the push condition checks the validity of the destination cell.
- If the box starts on the target, the algorithm will never enter the push detection branch; however, the initial state would already satisfy the goal, and the loop would eventually return
0pushes (the outer loop would finish without finding a push, and the final-1would be returned only if the target is unreachable). - Multiple reachable player positions without moving the box are explored through the
todoset, ensuring that the player can navigate around obstacles to find a viable pushing position. - Unreachable configurations lead to exhaustion of both
todoandnext, after which the function returns-1.
Performance Optimizations
The implementation incorporates several techniques that keep the search efficient:
- The direction vectors are stored in a single tuple
deltas, allowing the loop to generate(dx, dy)pairs without constructing separate lists. - All membership tests (
in valid,in seen) are performed on hash sets, providing average-case constant-time lookups. - The BFS is performed layer by layer using two sets (
todoandnext) rather than a queue that stores distance information, which reduces memory overhead. - By inserting ordinary player moves directly into
todoand marking them as seen immediately, the algorithm avoids redundant expansions of identical player positions within the same push layer. - Early termination occurs as soon as the box reaches the target, preventing unnecessary exploration of deeper layers.
These choices collectively ensure that the search explores only distinct configurations and stops at the first optimal solution.
ELI5 - Simplified Explanation
Imagine a big square floor made of tiles. Some tiles are walls where you cannot walk, one tile has a heavy box, one tile is the spot where the box needs to go, and one tile is where you are standing. The goal is to push the box onto that special spot by walking around it and nudging it across the floor.
The computer looks at the whole floor first to find where the box, the target spot, and you are hiding. It treats the floor like a map where some spaces are safe for walking and others are blocked.
To solve the puzzle, the computer keeps track of where both you and the box are at the same time. You can walk to any empty space nearby, but you cannot walk through walls. If you walk right up to the box, you can nudge it forward into the next space, as long as that space is empty and not a wall.
The computer tries every possible way to walk around and push the box. It remembers every position it has already checked so it does not walk in circles forever. It keeps moving, pushing the box step by step, until it finally slides the box right onto the target spot. If it tries every single path and still cannot get the box onto the target, it knows the puzzle is impossible to solve.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 591: Tag Validator
- problem 689: Maximum Sum of 3 Non-Overlapping Subarrays
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality