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
- 56 lines of Python from the credited upstream file 1210.py.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- No explicit 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.
1from enum import IntEnum2 3 4class Pos(IntEnum):5 HORIZONTAL = 06 VERTICAL = 17 8 9class Solution:10 def minimumMoves(self, grid: list[list[int]]) -> int:11 n = len(grid)12 ans = 013 14 15 q = collections.deque([(0, 0, Pos.HORIZONTAL)])16 seen = {(0, 0, Pos.HORIZONTAL)}17 18 def canMoveRight(x: int, y: int, pos: Pos) -> bool:19 if pos == Pos.HORIZONTAL:20 return y + 2 < n and not grid[x][y + 2]21 return y + 1 < n and not grid[x][y + 1] and not grid[x + 1][y + 1]22 23 def canMoveDown(x: int, y: int, pos: Pos) -> bool:24 if pos == Pos.VERTICAL:25 return x + 2 < n and not grid[x + 2][y]26 return x + 1 < n and not grid[x + 1][y] and not grid[x + 1][y + 1]27 28 def canRotateClockwise(x: int, y: int, pos: Pos) -> bool:29 return (pos == Pos.HORIZONTAL and x + 1 < n and30 not grid[x + 1][y + 1] and not grid[x + 1][y])31 32 def canRotateCounterclockwise(x: int, y: int, pos: Pos) -> bool:33 return (pos == Pos.VERTICAL and y + 1 < n and34 not grid[x + 1][y + 1] and not grid[x][y + 1])35 36 while q:37 for _ in range(len(q)):38 x, y, pos = q.popleft()39 if x == n - 1 and y == n - 2 and pos == Pos.HORIZONTAL:40 return ans41 if canMoveRight(x, y, pos) and (x, y + 1, pos) not in seen:42 q.append((x, y + 1, pos))43 seen.add((x, y + 1, pos))44 if canMoveDown(x, y, pos) and (x + 1, y, pos) not in seen:45 q.append((x + 1, y, pos))46 seen.add((x + 1, y, pos))47 newPos = Pos.VERTICAL if pos == Pos.HORIZONTAL else Pos.HORIZONTAL48 if ((canRotateClockwise(x, y, pos) or49 canRotateCounterclockwise(x, y, pos)) and50 (x, y, newPos) not in seen):51 q.append((x, y, newPos))52 seen.add((x, y, newPos))53 ans += 154 55 return -156