#1263

Minimum Moves to Move a Box to Their Target Location

Hard
ArrayBreadth-First SearchHeap (Priority Queue)MatrixBreadth-First SearchState Space Exploration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses BFS to find the shortest path for the player while ensuring the box can be pushed to the target. This method efficiently tracks the states and avoids unnecessary explorations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize BFS with the player's position and the box's position.
  2. 2Step 2: For each state, check if the box can be pushed in any direction and if the player can reach the new box position.
  3. 3Step 3: Continue until the box reaches the target or all possibilities are exhausted.
solution.py30 lines
1from collections import deque
2
3def minPushBox(grid):
4    m, n = len(grid), len(grid[0])
5    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
6    start = (0, 0, 0, 0)
7    for i in range(m):
8        for j in range(n):
9            if grid[i][j] == 'S':
10                start = (i, j)
11            elif grid[i][j] == 'B':
12                box = (i, j)
13            elif grid[i][j] == 'T':
14                target = (i, j)
15    queue = deque([(start[0], start[1], box[0], box[1], 0)])
16    visited = set()
17    visited.add((start[0], start[1], box[0], box[1]))
18
19    while queue:
20        px, py, bx, by, pushes = queue.popleft()
21        if (bx, by) == target:
22            return pushes
23        for dx, dy in directions:
24            nbx, nby = bx + dx, by + dy
25            if 0 <= nbx < m and 0 <= nby < n and grid[nbx][nby] != '#':
26                if (px, py) == (bx - dx, by - dy):
27                    if (px, py) != (bx, by):
28                        queue.append((bx, by, nbx, nby, pushes + 1))
29                        visited.add((bx, by, nbx, nby))
30    return -1

Complexity note: The time complexity is O(n) because we only explore valid states of the player and box, avoiding unnecessary checks. The space complexity is O(n) due to the queue and visited set storing states.

  • 1Understanding the grid structure is crucial for navigating the player and box.
  • 2Identifying valid moves and ensuring the player can reach the box before pushing it is key.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.