HardBreadth-First SearchGraphMatrix

Minimum Moves to Move a Box to Their Target Location

LeetCode
1 approach, code in all languages

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].length
  • 1 ≤ m, n ≤ 20
  • The grid contains exactly one 'S', one 'B', and one 'T'
  • Every cell is one of '.', '#', 'S', 'B', 'T'
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now