Problem
In an n*n
grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0)
and (0, 1)
. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2)
and (n-1, n-1)
.
In one move the snake can:
-
Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
-
Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
-
Rotate clockwise if it’s in a horizontal position and the two cells under it are both empty. In that case the snake moves from
(r, c)
and(r, c+1)
to(r, c)
and(r+1, c)
. -
Rotate counterclockwise if it’s in a vertical position and the two cells to its right are both empty. In that case the snake moves from
(r, c)
and(r+1, c)
to(r, c)
and(r, c+1)
.
Return the minimum number of moves to reach the target.
If there is no way to reach the target, return -1
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
2 <= n <= 100
0 <= grid[i][j] <= 1
- It is guaranteed that the snake starts at empty cells.
Solution
Method 1 – BFS with State Encoding
Intuition
We model the snake’s position as a state: the head’s coordinates and orientation (horizontal or vertical). BFS explores all possible moves and rotations, ensuring the shortest path to the target is found.
Approach
- Use BFS to explore states:
(row, col, orientation)
where orientation is 0 (horizontal) or 1 (vertical). - For each state, try moving right, down, and rotating if possible.
- Mark visited states to avoid cycles.
- Stop when the snake reaches the target position and orientation.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, as each state is visited at most once and there are up to2*n*n
states. - 🧺 Space complexity:
O(n^2)
, for the visited set and BFS queue.