#1210

Minimum Moves to Reach Target with Rotations

Hard
ArrayBreadth-First SearchMatrixBreadth-First SearchState Management
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution uses Breadth-First Search (BFS) to explore the grid efficiently. It tracks the snake's position and orientation, ensuring that we only explore valid moves and rotations, minimizing the number of moves needed to reach the target.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a queue for BFS with the starting position and orientation of the snake.
  2. 2Step 2: Use a set to track visited states (position and orientation) to avoid cycles.
  3. 3Step 3: For each position, explore all valid moves and rotations, adding them to the queue with an incremented move count.
  4. 4Step 4: If the target position is reached, return the number of moves; if the queue is exhausted without finding the target, return -1.
solution.py34 lines
1from collections import deque
2
3def minMoves(grid):
4    n = len(grid)
5    if grid[0][0] == 1 or grid[n-1][n-1] == 1: return -1
6    queue = deque([(0, 0, 0)])  # (row, col, orientation)
7    visited = set((0, 0, 0))
8    moves = 0
9    while queue:
10        for _ in range(len(queue)):
11            r, c, o = queue.popleft()
12            if (r, c) == (n-1, n-2) and o == 0: return moves
13            # Move right
14            if c + 1 < n and grid[r][c + 1] == 0:
15                if o == 0 and (r, c + 1, 0) not in visited:
16                    visited.add((r, c + 1, 0))
17                    queue.append((r, c + 1, 0))
18            # Move down
19            if r + 1 < n and grid[r + 1][c] == 0:
20                if o == 1 and (r + 1, c, 1) not in visited:
21                    visited.add((r + 1, c, 1))
22                    queue.append((r + 1, c, 1))
23            # Rotate clockwise
24            if o == 0 and r + 1 < n and grid[r + 1][c] == 0 and grid[r + 1][c + 1] == 0:
25                if (r, c, 1) not in visited:
26                    visited.add((r, c, 1))
27                    queue.append((r, c, 1))
28            # Rotate counterclockwise
29            if o == 1 and c + 1 < n and grid[r][c + 1] == 0 and grid[r + 1][c + 1] == 0:
30                if (r, c, 0) not in visited:
31                    visited.add((r, c, 0))
32                    queue.append((r, c, 0))
33        moves += 1
34    return -1

Complexity note: The complexity is O(n²) due to the BFS exploring the grid, but we also store visited states which can grow with the number of unique positions and orientations.

  • 1The snake's orientation adds complexity to the problem, requiring careful management of its state.
  • 2BFS is particularly effective for shortest path problems in unweighted grids.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.