Minimum Moves to Move a Box to Their Target Location

HardGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A warehouse is an m x n grid of characters: '#' is a wall, '.' is floor, 'S' is the player, 'B' is the single box, and 'T' is the target cell. The cells marked S, B, and T are floor as well. The player walks up, down, left, or right onto floor cells, and can never walk through walls or through the box. To **push** the box, the player must stand on the cell directly next to the box and move toward it; the box then slides one cell in that direction, which must be floor inside the grid, and the player ends up where the box was. Return the minimum number of **pushes** needed to get the box onto the target. Walking steps are free. If it is impossible, return -1.

Examples

Input: grid = [["#","#","#","#","#","#"],["#","T","#","#","#","#"],["#",".",".","B",".","#"],["#",".","#","#",".","#"],["#",".",".",".","S","#"],["#","#","#","#","#","#"]]
Output: 3
The player walks around, pushes the box left twice to column 1 of row 2, then pushes it up once onto T.
Input: grid = [["#","#","#","#","#","#"],["#","T","#","#","#","#"],["#",".",".","B",".","#"],["#","#","#","#",".","#"],["#",".",".",".","S","#"],["#","#","#","#","#","#"]]
Output: -1
The box can be pushed left to column 1, but the cell below it is now a wall, so nobody can push it up onto T.
Input: grid = [["#","#","#","#","#","#"],["#","T",".",".","#","#"],["#",".","#","B",".","#"],["#",".",".",".",".","#"],["#",".",".",".","S","#"],["#","#","#","#","#","#"]]
Output: 5
Push down, left, left, up, up.

Constraints

  • m == grid.length, n == grid[i].length
  • 1 <= m, n <= 20
  • grid contains only '.', '#', 'S', 'T', and 'B'
  • There is exactly one 'S', one 'B', and one 'T'

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems