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:
'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).'.' represents the floor which means a free cell to walk.'#' represents the wall which means an obstacle (impossible to walk there).'B' and one target cell 'T' in the grid.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 <= 20grid contains only characters '.', '#', 'S', 'T', or 'B'.'S', 'B', and 'T' in the grid.Problem Overview: You are given a grid with walls, a player, a box, and a target. The player can move freely but can only push (not pull) the box. The task is to compute the minimum number of pushes required to move the box to the target cell.
Approach 1: Breadth-First Search with State Tracking (O((mn)^2) time, O((mn)^2) space)
Model the puzzle as a state search where each state contains both the box position and the player position. The BFS queue prioritizes states by the number of pushes, not simple movements. When the player moves behind the box and pushes it, a new state is created with the updated box location. Before each push, run a reachability check to confirm the player can walk to the required pushing position without crossing the box or walls. A visited set like (boxRow, boxCol, playerRow, playerCol) prevents revisiting states. This approach relies heavily on Breadth-First Search across a matrix grid to guarantee the minimum pushes.
Approach 2: A* Search for Optimal Pushes (O((mn)^2 log(mn)) time, O((mn)^2) space)
A* improves the search by guiding exploration toward the target using a heuristic. Each state still contains the box and player coordinates, but states are stored in a priority queue ordered by f = pushes + heuristic. A common heuristic is the Manhattan distance from the box to the target. This does not overestimate the required pushes, so the search remains optimal. Instead of expanding states purely level by level like BFS, A* prioritizes promising states and typically explores fewer configurations. The implementation uses a priority queue to efficiently select the next state with the smallest estimated cost.
Recommended for interviews: BFS with state tracking is the most common expected solution. It clearly models the puzzle as a graph search and guarantees the minimum number of pushes. Interviewers usually want to see correct state representation and reachability checks. Mentioning A* as an optimization shows deeper search algorithm knowledge and strong problem-solving maturity.
This approach uses a BFS strategy, commonly used for exploring shortest paths, which also tracks states consisting of the player's and the box’s positions along with the number of pushes made. Each state can be represented as a tuple consisting of these values. The BFS runs until the box reaches its target position or all possible states are exhausted. To ensure efficiency, already visited states are stored and checked before exploration to prevent cyclic paths.
This Python solution uses a BFS approach to explore all possible ways the player can push the box to the target. It tracks the player's and the box's current positions and checks all possible moves. The BFS ensures the shortest path is found by exploring in layers. The main components include state validation, tracking visited states, and maintaining a queue for the BFS exploration.
Time Complexity: O(m * n) due to traversing each cell, where m and n are the grid dimensions.
Space Complexity: O(m * n) for the space required to store states in the queue and visited set.
This approach optimizes the BFS approach even further by using the A* search algorithm, which is a popular choice for pathfinding and graph traversal. In A*, each state is evaluated with a heuristic to estimate the minimum cost to reach the target. The heuristic can be the Manhattan distance from the box to the target which guides the search more directly towards optimal solutions more efficiently.
This C++ solution uses the A* algorithm which is advantageous over BFS by utilizing a heuristic approach. The heuristic guides the exploration to significantly reduce unnecessary steps by taking into consideration the Manhattan distance to the target. The state of the game is abstracted into a struct and processed through a priority queue, ensuring that the paths with the least cost are expanded first.
C++
JavaScript
Time Complexity: O((m * n)^2) in the worst case because of priority queue operations and heuristic calculations.
Space Complexity: O(m * n) for the storage of states.
We consider the player's position and the box's position as a state, i.e., (s_i, s_j, b_i, b_j), where (s_i, s_j) is the player's position, and (b_i, b_j) is the box's position. In the code implementation, we define a function f(i, j), which maps the two-dimensional coordinates (i, j) to a one-dimensional state number, i.e., f(i, j) = i times n + j, where n is the number of columns in the grid. So the player and the box's state is (f(s_i, s_j), f(b_i, b_j)).
First, we traverse the grid to find the initial positions of the player and the box, denoted as (s_i, s_j) and (b_i, b_j).
Then, we define a double-ended queue q, where each element is a triplet (f(s_i, s_j), f(b_i, b_j), d), indicating that the player is at (s_i, s_j), the box is at (b_i, b_j), and d pushes have been made. Initially, we add (f(s_i, s_j), f(b_i, b_j), 0) to the queue q.
Additionally, we use a two-dimensional array vis to record whether each state has been visited. Initially, vis[f(s_i, s_j), f(b_i, b_j)] is marked as visited.
Next, we start the breadth-first search.
In each step of the search, we take out the queue head element (f(s_i, s_j), f(b_i, b_j), d), and check whether grid[b_i][b_j] = 'T' is satisfied. If it is, it means the box has been pushed to the target position, and now d can be returned as the answer.
Otherwise, we enumerate the player's next move direction. The player's new position is denoted as (s_x, s_y). If (s_x, s_y) is a valid position, we judge whether (s_x, s_y) is the same as the box's position (b_i, b_j):
(b_x, b_y). If (b_x, b_y) is a valid position, and the state (f(s_x, s_y), f(b_x, b_y)) has not been visited, then we add (f(s_x, s_y), f(b_x, b_y), d + 1) to the end of the queue q, and mark vis[f(s_x, s_y), f(b_x, b_y)] as visited.(f(s_x, s_y), f(b_i, b_j)) has been visited. If it has not been visited, then we add (f(s_x, s_y), f(b_i, b_j), d) to the head of the queue q, and mark vis[f(s_x, s_y), f(b_i, b_j)] as visited.We continue the breadth-first search until the queue is empty.
Note, if the box is pushed, the push count
dneeds to be incremented by1, and the new state is added to the end of the queueq. If the box is not pushed, the push countdremains unchanged, and the new state is added to the head of the queueq.
Finally, if no valid push scheme is found, then return -1.
The time complexity is O(m^2 times n^2), and the space complexity is O(m^2 times n^2). Where m and n are the number of rows and columns in the grid, respectively.
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Breadth-First Search (BFS) with State Tracking | Time Complexity: O(m * n) due to traversing each cell, where m and n are the grid dimensions. |
| A* Search for Optimal Pushes | Time Complexity: O((m * n)^2) in the worst case because of priority queue operations and heuristic calculations. |
| Double-ended Queue + BFS | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| BFS with State Tracking | O((mn)^2) | O((mn)^2) | Standard solution for interviews. Guarantees minimum pushes and easier to reason about. |
| A* Search with Priority Queue | O((mn)^2 log(mn)) | O((mn)^2) | When optimizing search exploration. Heuristic reduces explored states in large grids. |
花花酱 LeetCode 1263. Minimum Moves to Move a Box to Their Target Location - 刷题找工作 EP279 • Hua Hua • 3,698 views views
Watch 7 more video solutions →Practice Minimum Moves to Move a Box to Their Target Location with our built-in code editor and test cases.
Practice on FleetCode