Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minPushBox(vector<vector<char>>& grid) {4 const int m = grid.size();5 const int n = grid[0].size();6 vector<int> box;7 vector<int> player;8 vector<int> target;9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 if (grid[i][j] == 'B')13 box = {i, j};14 else if (grid[i][j] == 'S')15 player = {i, j};16 else if (grid[i][j] == 'T')17 target = {i, j};18 19 20 queue<tuple<int, int, int, int>> q{21 {{box[0], box[1], player[0], player[1]}}};22 vector<vector<vector<vector<bool>>>> seen(23 m, vector<vector<vector<bool>>>(24 n, vector<vector<bool>>(m, vector<bool>(n))));25 seen[box[0]][box[1]][player[0]][player[1]] = true;26 27 for (int step = 0; !q.empty(); ++step)28 for (int sz = q.size(); sz > 0; --sz) {29 const auto [boxX, boxY, playerX, playerY] = q.front();30 q.pop();31 if (boxX == target[0] && boxY == target[1])32 return step;33 for (int k = 0; k < 4; ++k) {34 const int nextBoxX = boxX + kDirs[k % 4][0];35 const int nextBoxY = boxY + kDirs[k % 4][1];36 if (isInvalid(grid, nextBoxX, nextBoxY))37 continue;38 if (seen[nextBoxX][nextBoxY][boxX][boxY])39 continue;40 const int fromX = boxX + kDirs[(k + 2) % 4][0];41 const int fromY = boxY + kDirs[(k + 2) % 4][1];42 if (isInvalid(grid, fromX, fromY))43 continue;44 if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) {45 seen[nextBoxX][nextBoxY][boxX][boxY] = true;46 q.emplace(nextBoxX, nextBoxY, boxX, boxY);47 }48 }49 }50 51 return -1;52 }53 54 private:55 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};56 57 58 bool canGoTo(const vector<vector<char>>& grid, int playerX, int playerY,59 int fromX, int fromY, int boxX, int boxY) {60 queue<pair<int, int>> q{{{playerX, playerY}}};61 vector<vector<bool>> seen(grid.size(), vector<bool>(grid[0].size()));62 seen[playerX][playerY] = true;63 64 while (!q.empty()) {65 const auto [i, j] = q.front();66 q.pop();67 if (i == fromX && j == fromY)68 return true;69 for (const auto& [dx, dy] : kDirs) {70 const int x = i + dx;71 const int y = j + dy;72 if (isInvalid(grid, x, y))73 continue;74 if (seen[x][y])75 continue;76 if (x == boxX && y == boxY)77 continue;78 q.emplace(x, y);79 seen[x][y] = true;80 }81 }82 83 return false;84 }85 86 bool isInvalid(const vector<vector<char>>& grid, int playerX, int playerY) {87 return playerX < 0 || playerX == grid.size() || playerY < 0 ||88 playerY == grid[0].size() || grid[playerX][playerY] == '#';89 }90};91