Problem 1263

Abstract / Summary

Move a player and a box on a grid to the box's target spot with the fewest steps while obeying movement rules.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
79 lines | 2422 bytes | submitted July 10, 2024 | GitHub   36% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (60k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Heap (Priority Queue)
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 todo if 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 valid set, 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 0 pushes (the outer loop would finish without finding a push, and the final -1 would be returned only if the target is unreachable).
  • Multiple reachable player positions without moving the box are explored through the todo set, ensuring that the player can navigate around obstacles to find a viable pushing position.
  • Unreachable configurations lead to exhaustion of both todo and next, 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 (todo and next) rather than a queue that stores distance information, which reduces memory overhead.
  • By inserting ordinary player moves directly into todo and 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.07 | σ = 1.76

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
25 links | 13 authors | 7 languages

Videos

1 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 solutions   July 10, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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