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
- 59 lines of Java from the credited upstream file 1210.java.
- 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 Pos { HORIZONTAL, VERTICAL }2 3class Solution {4 public int minimumMoves(int[][] grid) {5 record T(int x, int y, Pos pos) {}6 final int n = grid.length;7 Queue<T> q = new ArrayDeque<>(List.of(new T(0, 0, Pos.HORIZONTAL)));8 boolean[][][] seen = new boolean[n][n][2];9 seen[0][0][Pos.HORIZONTAL.ordinal()] = true;10 11 for (int step = 0; !q.isEmpty(); ++step)12 for (int sz = q.size(); sz > 0; --sz) {13 final int x = q.peek().x;14 final int y = q.peek().y;15 final Pos pos = q.poll().pos;16 if (x == n - 1 && y == n - 2 && pos == Pos.HORIZONTAL)17 return step;18 if (canMoveRight(grid, x, y, pos) && !seen[x][y + 1][pos.ordinal()]) {19 q.offer(new T(x, y + 1, pos));20 seen[x][y + 1][pos.ordinal()] = true;21 }22 if (canMoveDown(grid, x, y, pos) && !seen[x + 1][y][pos.ordinal()]) {23 q.offer(new T(x + 1, y, pos));24 seen[x + 1][y][pos.ordinal()] = true;25 }26 final Pos newPos = pos == Pos.HORIZONTAL ? Pos.VERTICAL : Pos.HORIZONTAL;27 if ((canRotateClockwise(grid, x, y, pos) || canRotateCounterclockwise(grid, x, y, pos)) &&28 !seen[x][y][newPos.ordinal()]) {29 q.offer(new T(x, y, newPos));30 seen[x][y][newPos.ordinal()] = true;31 }32 }33 34 return -1;35 }36 37 private boolean canMoveRight(int[][] grid, int x, int y, Pos pos) {38 if (pos == Pos.HORIZONTAL)39 return y + 2 < grid.length && grid[x][y + 2] == 0;40 return y + 1 < grid.length && grid[x][y + 1] == 0 && grid[x + 1][y + 1] == 0;41 }42 43 private boolean canMoveDown(int[][] grid, int x, int y, Pos pos) {44 if (pos == Pos.VERTICAL)45 return x + 2 < grid.length && grid[x + 2][y] == 0;46 return x + 1 < grid.length && grid[x + 1][y] == 0 && grid[x + 1][y + 1] == 0;47 }48 49 private boolean canRotateClockwise(int[][] grid, int x, int y, Pos pos) {50 return pos == Pos.HORIZONTAL && x + 1 < grid.length && grid[x + 1][y + 1] == 0 &&51 grid[x + 1][y] == 0;52 }53 54 private boolean canRotateCounterclockwise(int[][] grid, int x, int y, Pos pos) {55 return pos == Pos.VERTICAL && y + 1 < grid.length && grid[x + 1][y + 1] == 0 &&56 grid[x][y + 1] == 0;57 }58}59