1263. Minimum Moves to Move a Box to Their Target Location
Problem description:
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 a grid
of size m x n
, where each element is a wall, floor, or a box.
Your task is move the box 'B'
to the target position 'T'
under the following rules:
- Player is represented by character
'S'
and can move up, down, left, right in thegrid
if it is a floor (empy cell). - Floor is represented by character
'.'
that means free cell to walk. - Wall is represented by character
'#'
that means 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:
1 | Input: grid = [["#","#","#","#","#","#"], |
Solution:
Dijkstra, a node is (person, box)
tuple, weight is the number of moves
- First find all the positions and
set of free spots
, note everyplace is free spot except wall#
- Do BFS with heap, moves is the weight of edge
- For every direction to move person, there’re two cases
- New position is not box located:
Node(newPerson location, box)
not yet visited
Node(newPerson location)
is in free spot sets
note that we don’t have to increase move - New position is box located:
Node(newPerson location, newBox location)
not yet visited
Node(newBox location)
is in free spot sets
need to increase move because we move the box
- New position is not box located:
1 | class Solution: |
Two BFS: one to find if person could move to new position to push box; the other one to find box could move to target position
- Lets think that we have no person and we have to find the minimum path between box and the target. Easy right? Simple BFS.
- If you know how to solve the first part, what I actually do is modified first part with few constraints.
- I just check whether the box can be shifted to the new position(up, down, left, right)
- For it to be shifted to the new position the person has to be in a corresponding position right?
- So we check if the person can travel from his old position to his corresponding new position(using another BFS).
- If the person can travel to his new position than the box can be shifted, otherwise the box cannot be shifted.
- We keep repeating step 2 until we reach the target or it is not possible to move the box anymore.
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: