Problem solution · Java

Minimum Moves to Move a Box to Their Target Location

Minimum Moves to Move a Box to Their Target Location: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
88 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Minimum Moves to Move a Box to Their Target Location, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 88 lines of Java from the credited upstream file 1263.java.
  • The implementation visibly relies on sequence storage, work queue.
  • 7 loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Moves to Move a Box to Their Target Location · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int minPushBox(char[][] grid) {    record T(int boxX, int boxY, int playerX, int playerY) {}    final int m = grid.length;    final int n = grid[0].length;    int[] box = {-1, -1};    int[] player = {-1, -1};    int[] target = {-1, -1};     for (int i = 0; i < m; ++i)      for (int j = 0; j < n; ++j)        if (grid[i][j] == 'B')          box = new int[] {i, j};        else if (grid[i][j] == 'S')          player = new int[] {i, j};        else if (grid[i][j] == 'T')          target = new int[] {i, j};     Queue<T> q = new ArrayDeque<>(List.of(new T(box[0], box[1], player[0], player[1])));    boolean[][][][] seen = new boolean[m][n][m][n];    seen[box[0]][box[1]][player[0]][player[1]] = true;     for (int step = 0; !q.isEmpty(); ++step)      for (int sz = q.size(); sz > 0; --sz) {        final int boxX = q.peek().boxX;        final int boxY = q.peek().boxY;        final int playerX = q.peek().playerX;        final int playerY = q.poll().playerY;        if (boxX == target[0] && boxY == target[1])          return step;        for (int k = 0; k < 4; ++k) {          final int nextBoxX = boxX + DIRS[k][0];          final int nextBoxY = boxY + DIRS[k][1];          if (isInvalid(grid, nextBoxX, nextBoxY))            continue;          if (seen[nextBoxX][nextBoxY][boxX][boxY])            continue;          final int fromX = boxX + DIRS[(k + 2) % 4][0];          final int fromY = boxY + DIRS[(k + 2) % 4][1];          if (isInvalid(grid, fromX, fromY))            continue;          if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) {            seen[nextBoxX][nextBoxY][boxX][boxY] = true;            q.offer(new T(nextBoxX, nextBoxY, boxX, boxY));          }        }      }     return -1;  }   private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};   // Returns true if (playerX, playerY) can go to (fromX, fromY).  private boolean canGoTo(char[][] grid, int playerX, int playerY, int fromX, int fromY, int boxX,                          int boxY) {    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(playerX, playerY)));    boolean[][] seen = new boolean[grid.length][grid[0].length];    seen[playerX][playerY] = true;     while (!q.isEmpty()) {      final int i = q.peek().getKey();      final int j = q.poll().getValue();      if (i == fromX && j == fromY)        return true;      for (int[] dir : DIRS) {        final int x = i + dir[0];        final int y = j + dir[1];        if (isInvalid(grid, x, y))          continue;        if (seen[x][y])          continue;        if (x == boxX && y == boxY)          continue;        q.offer(new Pair<>(x, y));        seen[x][y] = true;      }    }     return false;  }   private boolean isInvalid(char[][] grid, int playerX, int playerY) {    return playerX < 0 || playerX == grid.length || playerY < 0 || playerY == grid[0].length ||        grid[playerX][playerY] == '#';  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗