Minimum Moves to Reach Target with Rotations - Problem

In an n×n grid, there is a snake that spans 2 cells and starts at the top-left corner at positions (0, 0) and (0, 1). The grid has empty cells represented by 0 and blocked cells represented by 1.

The snake wants to reach the target at the lower-right corner at positions (n-1, n-2) and (n-1, n-1).

In one move, the snake can:

  • Move right: Move one cell to the right if there are no blocked cells there
  • Move down: Move one cell down if there are no blocked cells there
  • Rotate clockwise: If in horizontal position and the two cells under it are both empty, snake moves from (r, c), (r, c+1) to (r, c), (r+1, c)
  • Rotate counterclockwise: If in vertical position and the two cells to its right are both empty, snake moves from (r, c), (r+1, c) to (r, c), (r, c+1)

Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1.

Input & Output

Example 1 — Basic Case
$ 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: Snake starts at (0,0)-(0,1) horizontal and needs to reach (5,4)-(5,5). Through a series of moves and rotations, minimum 11 moves are needed.
Example 2 — Simple Grid
$ 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: Snake cannot reach the target due to blocked paths, so return -1.
Example 3 — Small Grid
$ Input: grid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 4
💡 Note: In a 3×3 grid, snake needs 4 moves: right, rotate, down, rotate to reach (2,1)-(2,2).

Constraints

  • 2 ≤ n ≤ 100
  • grid.length == n
  • grid[i].length == n
  • grid[i][j] is 0 or 1

Visualization

Tap to expand
Snake Navigation: From Start to TargetStarting PositionSS0110000movesPossible Actions→ Move Right↓ Move Down↻ Rotate Clockwise↺ Rotate CounterTarget PositionTT(n-1, n-2) and (n-1, n-1)Goal: Find minimum number of moves to reach targetLegend: Green=Snake, Red=Blocked, Gray=Empty, Orange=Target
Understanding the Visualization
1
Input Grid
n×n grid with blocked cells (1) and empty cells (0)
2
Snake Movement
Snake can move right, down, or rotate based on available space
3
Target Reached
Find minimum moves to reach bottom-right corner
Key Takeaway
🎯 Key Insight: Model snake state as (position + orientation) and use BFS for guaranteed minimum path
Asked in
Google 15 Facebook 12 Amazon 8
32.0K Views
Medium Frequency
~35 min Avg. Time
853 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen