Approach
Breadth-first search
For Minimum Moves to Reach Target with Rotations, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 61 lines of C++ from the credited upstream file 1210.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 2 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.
Use this to learn the idea, then write your own version.
1enum class Pos { kHorizontal, kVertical };2 3class Solution {4 public:5 int minimumMoves(vector<vector<int>>& grid) {6 const int n = grid.size();7 queue<tuple<int, int, Pos>> q{{{0, 0, Pos::kHorizontal}}};8 vector<vector<vector<bool>>> seen(n,9 vector<vector<bool>>(n, vector<bool>(2)));10 seen[0][0][static_cast<int>(Pos::kHorizontal)] = true;11 12 auto canMoveRight = [&](int x, int y, Pos pos) -> bool {13 if (pos == Pos::kHorizontal)14 return y + 2 < n && !grid[x][y + 2];15 return y + 1 < n && !grid[x][y + 1] && !grid[x + 1][y + 1];16 };17 18 auto canMoveDown = [&](int x, int y, Pos pos) -> bool {19 if (pos == Pos::kVertical)20 return x + 2 < n && !grid[x + 2][y];21 return x + 1 < n && !grid[x + 1][y] && !grid[x + 1][y + 1];22 };23 24 auto canRotateClockwise = [&](int x, int y, Pos pos) -> bool {25 return pos == Pos::kHorizontal && x + 1 < n && !grid[x + 1][y + 1] &&26 !grid[x + 1][y];27 };28 29 auto canRotateCounterclockwise = [&](int x, int y, Pos pos) -> bool {30 return pos == Pos::kVertical && y + 1 < n && !grid[x + 1][y + 1] &&31 !grid[x][y + 1];32 };33 34 for (int step = 0; !q.empty(); ++step)35 for (int sz = q.size(); sz > 0; --sz) {36 const auto [x, y, pos] = q.front();37 q.pop();38 if (x == n - 1 && y == n - 2 && pos == Pos::kHorizontal)39 return step;40 if (canMoveRight(x, y, pos) && !seen[x][y + 1][static_cast<int>(pos)]) {41 q.emplace(x, y + 1, pos);42 seen[x][y + 1][static_cast<int>(pos)] = true;43 }44 if (canMoveDown(x, y, pos) && !seen[x + 1][y][static_cast<int>(pos)]) {45 q.emplace(x + 1, y, pos);46 seen[x + 1][y][static_cast<int>(pos)] = true;47 }48 const Pos newPos =49 pos == Pos::kHorizontal ? Pos::kVertical : Pos::kHorizontal;50 if ((canRotateClockwise(x, y, pos) ||51 canRotateCounterclockwise(x, y, pos)) &&52 !seen[x][y][static_cast<int>(newPos)]) {53 q.emplace(x, y, newPos);54 seen[x][y][static_cast<int>(newPos)] = true;55 }56 }57 58 return -1;59 }60};61