Skip to content

1263. Minimum Moves to Move a Box to Their Target Location 👍

  • Time: $O(m^2n^2)$
  • Space: $O(m^2n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Solution {
 public:
  int minPushBox(vector<vector<char>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector<int> box;
    vector<int> player;
    vector<int> target;

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j] == 'B')
          box = {i, j};
        else if (grid[i][j] == 'S')
          player = {i, j};
        else if (grid[i][j] == 'T')
          target = {i, j};

    int ans = 0;
    // (boxX, boxY, playerX, playerY)
    queue<tuple<int, int, int, int>> q{
        {{box[0], box[1], player[0], player[1]}}};
    vector<vector<vector<vector<bool>>>> seen(
        m, vector<vector<vector<bool>>>(
               n, vector<vector<bool>>(m, vector<bool>(n))));
    seen[box[0]][box[1]][player[0]][player[1]] = true;

    while (!q.empty()) {
      for (int sz = q.size(); sz > 0; --sz) {
        const auto [boxX, boxY, playerX, playerY] = q.front();
        q.pop();
        if (boxX == target[0] && boxY == target[1])
          return ans;
        for (int k = 0; k < 4; ++k) {
          const int nextBoxX = boxX + dirs[k];
          const int nextBoxY = boxY + dirs[k + 1];
          if (isInvalid(grid, nextBoxX, nextBoxY))
            continue;
          if (seen[nextBoxX][nextBoxY][boxX][boxY])
            continue;
          const int fromX = boxX + dirs[(k + 2) % 4];
          const int fromY = boxY + dirs[(k + 3) % 4];
          if (isInvalid(grid, fromX, fromY))
            continue;
          if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) {
            seen[nextBoxX][nextBoxY][boxX][boxY] = true;
            q.emplace(nextBoxX, nextBoxY, boxX, boxY);
          }
        }
      }
      ++ans;
    }

    return -1;
  }

 private:
  const vector<int> dirs{0, 1, 0, -1, 0};

  // Returns true if (playerX, playerY) can go to (fromX, fromY).
  bool canGoTo(const vector<vector<char>>& grid, int playerX, int playerY,
               int fromX, int fromY, int boxX, int boxY) {
    queue<pair<int, int>> q{{{playerX, playerY}}};
    vector<vector<bool>> seen(grid.size(), vector<bool>(grid[0].size()));
    seen[playerX][playerY] = true;

    while (!q.empty()) {
      const auto [i, j] = q.front();
      q.pop();
      if (i == fromX && j == fromY)
        return true;
      for (int k = 0; k < 4; ++k) {
        const int x = i + dirs[k];
        const int y = j + dirs[k + 1];
        if (isInvalid(grid, x, y))
          continue;
        if (seen[x][y])
          continue;
        if (x == boxX && y == boxY)
          continue;
        q.emplace(x, y);
        seen[x][y] = true;
      }
    }

    return false;
  }

  bool isInvalid(const vector<vector<char>>& grid, int playerX, int playerY) {
    return playerX < 0 || playerX == grid.size() || playerY < 0 ||
           playerY == grid[0].size() || grid[playerX][playerY] == '#';
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class Solution {
  public int minPushBox(char[][] grid) {
    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};

    int ans = 0;
    // (boxX, boxY, playerX, playerY)
    Queue<int[]> q =
        new ArrayDeque<>(Arrays.asList(new int[] {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;

    while (!q.isEmpty()) {
      for (int sz = q.size(); sz > 0; --sz) {
        final int boxX = q.peek()[0];
        final int boxY = q.peek()[1];
        final int playerX = q.peek()[2];
        final int playerY = q.poll()[3];
        if (boxX == target[0] && boxY == target[1])
          return ans;
        for (int k = 0; k < 4; ++k) {
          final int nextBoxX = boxX + dirs[k];
          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];
          final int fromY = boxY + dirs[(k + 3) % 4];
          if (isInvalid(grid, fromX, fromY))
            continue;
          if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) {
            seen[nextBoxX][nextBoxY][boxX][boxY] = true;
            q.offer(new int[] {nextBoxX, nextBoxY, boxX, boxY});
          }
        }
      }
      ++ans;
    }

    return -1;
  }

  private static final int[] dirs = {0, 1, 0, -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<>(Arrays.asList(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 k = 0; k < 4; ++k) {
        final int x = i + dirs[k];
        final int y = j + dirs[k + 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] == '#';
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution:
  def minPushBox(self, grid: List[List[chr]]) -> int:
    dirs = [0, 1, 0, -1, 0]
    m = len(grid)
    n = len(grid[0])

    for i in range(m):
      for j in range(n):
        if grid[i][j] == 'B':
          box = (i, j)
        elif grid[i][j] == 'S':
          player = (i, j)
        elif grid[i][j] == 'T':
          target = (i, j)

    def isInvalid(playerX: int, playerY: int) -> bool:
      return playerX < 0 or playerX == m or playerY < 0 or playerY == n \
          or grid[playerX][playerY] == '#'

    # Returns true if (playerX, playerY) can go to (fromX, fromY).
    def canGoTo(playerX: int, playerY: int, fromX: int, fromY: int, boxX: int, boxY: int) -> bool:
      q = collections.deque([(playerX, playerY)])
      seen = {(playerX, playerY)}

      while q:
        i, j = q.popleft()
        if i == fromX and j == fromY:
          return True
        for k in range(4):
          x = i + dirs[k]
          y = j + dirs[k + 1]
          if isInvalid(x, y):
            continue
          if (x, y) in seen:
            continue
          if x == boxX and y == boxY:
            continue
          q.append((x, y))
          seen.add((x, y))

      return False

    ans = 0
    # (boxX, boxY, playerX, playerY)
    q = collections.deque([(box[0], box[1], player[0], player[1])])
    seen = {(box[0], box[1], player[0], player[1])}

    while q:
      for _ in range(len(q)):
        boxX, boxY, playerX, playerY = q.popleft()
        if boxX == target[0] and boxY == target[1]:
          return ans
        for k in range(4):
          nextBoxX = boxX + dirs[k]
          nextBoxY = boxY + dirs[k + 1]
          if isInvalid(nextBoxX, nextBoxY):
            continue
          if (nextBoxX, nextBoxY, boxX, boxY) in seen:
            continue
          fromX = boxX + dirs[(k + 2) % 4]
          fromY = boxY + dirs[(k + 3) % 4]
          if isInvalid(fromX, fromY):
            continue
          if canGoTo(playerX, playerY, fromX, fromY, boxX, boxY):
            q.append((nextBoxX, nextBoxY, boxX, boxY))
            seen.add((nextBoxX, nextBoxY, boxX, boxY))
      ans += 1

    return -1