Minimum Moves to Move a Box to Their Target Location
1 approach, code in every language
Problem description
You are given a grid where each cell is floor ('.'), a wall ('#'), the player's starting cell ('S'), the box ('B'), or the target cell ('T'). The player wants to push the single box onto the target.
The player walks one step at a time in the four cardinal directions onto floor cells. To push the box, the player must stand directly on the side opposite the push direction and step into the box, which shifts the box one cell forward; that destination cell must be floor. Each push counts as one move while walking is free. Return the minimum number of pushes to get the box onto the target, or -1 if it cannot be done.
Example 1
Input: grid = [["#","#","#","#","#","#"],["#","T","#","#","#","#"],["#",".",".","B",".","#"],["#",".","#","#",".","#"],["#",".",".",".","S","#"],["#","#","#","#","#","#"]]
Output: 3
The player maneuvers around the box and pushes it three times to land it on the target.
Example 2
Input: grid = [["#","#","#","#","#","#"],["#","T","#","#","#","#"],["#",".",".","B",".","#"],["#","#","#","#",".","#"],["#",".",".",".","S","#"],["#","#","#","#","#","#"]]
Output: -1
A wall row blocks the player from ever standing below the box to push it up toward the target.
Constraints
m == grid.length and n == grid[i].length1 ≤ m, n ≤ 20The grid contains exactly one 'S', one 'B', and one 'T'Every cell is one of '.', '#', 'S', 'B', 'T'
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free