Minimum Moves to Reach Target with Rotations - Problem
Imagine controlling a snake robot that spans exactly 2 cells and needs to navigate through an obstacle course! Your snake starts at the top-left corner of an nรn grid, initially positioned horizontally at cells (0, 0) and (0, 1).
The grid contains:
- Empty cells (represented by
0) - safe to move through - Blocked cells (represented by
1) - obstacles that block movement
Your goal is to reach the bottom-right corner at positions (n-1, n-2) and (n-1, n-1) in the minimum number of moves.
The snake can perform these moves:
- Move Right: Both cells move one position right (if no obstacles)
- Move Down: Both cells move one position down (if no obstacles)
- Rotate Clockwise: When horizontal, rotate to vertical if both cells below are empty
- Rotate Counterclockwise: When vertical, rotate to horizontal if both cells to the right are empty
Return the minimum moves needed, or -1 if impossible to reach the target.
Input & Output
example_1.py โ Simple 3x3 Grid
$
Input:
grid = [[0,0,0,0,0,1],[1,1,0,0,1,0],[0,0,0,0,1,1],[0,0,1,0,1,0],[0,1,1,0,0,0],[0,1,1,0,0,0]]
โบ
Output:
11
๐ก Note:
The snake needs to navigate around obstacles using a combination of moves and rotations. The optimal path requires 11 moves to reach the target position.
example_2.py โ Simple Path
$
Input:
grid = [[0,0,1,1,1,1],[0,0,0,0,1,1],[1,1,0,0,0,1],[1,1,1,0,0,0],[0,1,1,0,0,0],[0,1,1,0,0,0]]
โบ
Output:
-1
๐ก Note:
There is no valid path for the snake to reach the target due to the obstacle layout blocking all possible routes.
example_3.py โ Minimum Grid
$
Input:
grid = [[0,0,0],[0,1,0],[0,0,0]]
โบ
Output:
4
๐ก Note:
In a 3x3 grid with one obstacle, the snake can reach target (2,1)-(2,2) in 4 moves: right, down, right, down.
Constraints
- 2 โค grid.length โค 100
- 2 โค grid[i].length โค 100
- grid[i][j] is 0 or 1
- It is guaranteed that the snake and target area are empty
- The snake always starts horizontally at (0,0) and (0,1)
- Target is always at (n-1, n-2) and (n-1, n-1) horizontally
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Snake starts horizontally at top-left: (0,0)-(0,1)
2
Explore Moves
BFS explores right, down, and rotate moves simultaneously
3
Track States
Each unique (position, orientation) combination is a state
4
Find Shortest
First time we reach target state gives minimum moves
Key Takeaway
๐ฏ Key Insight: By treating each (position, orientation) as a unique state and using BFS, we guarantee finding the shortest path through the state space in O(nยฒ) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code