Minimum Moves to Move a Box to Their Target Location - Problem

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:

  • The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).
  • The character '.' represents the floor which means a free cell to walk.
  • The character '#' represents the wall which means an obstacle (impossible to walk there).
  • There is only one box 'B' and one target cell 'T' in the grid.
  • 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.

Input & Output

Example 1 — Basic Push
$ Input: grid = [["#",".","#"],[".","T","B"],["#","S","#"]]
Output: 1
💡 Note: Player S can reach position (1,0) to push box B from (1,2) to target T at (1,1) in 1 push
Example 2 — Multiple Pushes
$ Input: grid = [["#","#","#","#","#","#"],["#","T","#","#","#","#"],["#",".",".","B",".","#"],["#",".","#","#",".","#"],["#",".",".",".","S","#"],["#","#","#","#","#","#"]]
Output: 3
💡 Note: Player must navigate around walls and push box 3 times to reach target
Example 3 — Impossible Case
$ Input: grid = [["#","#","#"],["#","T","#"],["#","B","#"],["#","S","#"]]
Output: -1
💡 Note: Box is surrounded by walls and cannot be pushed to target

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 20
  • grid contains only characters '.', '#', 'S', 'B', 'T'
  • There is only one of each character 'S', 'B', 'T' in the grid

Visualization

Tap to expand
INPUT GRIDBFS ALGORITHMFINAL RESULT#.#.TB#S#Player S must pushBox B to Target T1Initial State(player: (2,1), box: (1,2))2Check Push UPCan player reach (1,2) → (1,1)?3Valid PushNew state: pushes = 14Target ReachedBox at target, return 11 PUSHMinimum SolutionBox successfully movedfrom (1,2) to target (1,1)in optimal 1 pushKey Insight:BFS on (player_position, box_position) states guarantees minimum pushes by exploring level by levelTutorialsPoint - Minimum Moves to Move a Box to Their Target Location | BFS State Search
Asked in
Google 8 Amazon 12 Microsoft 6 Apple 4
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen