#1263
Minimum Moves to Move a Box to Their Target Location
candidate master · 1440 · lc hard +32 · verified · 49.5% accepted · 887 likes · top 36%
Description
In a Sokoban-inspired puzzle, a player pushes a box through a grid to reach a target.
The m x n grid uses these characters:
- 'S' — the player's starting position (moves freely through empty cells).
- '.' — a free floor tile.
- '#' — an impassable wall.
- 'B' — the box (exactly one).
- 'T' — the target (exactly one).
A push occurs when the player moves into the box from one side, shoving it one step in the same direction — but only if the box's destination is empty. The player cannot walk through the box.
Return the minimum number of pushes to move the box onto the target, or -1 if impossible.
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.
Code
1
2
3