#2850
Minimum Moves to Spread Stones Over Grid
MediumArrayDynamic ProgrammingBacktrackingBit ManipulationMatrixBitmaskBacktrackingDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a backtracking approach to efficiently explore the distribution of stones. It leverages the small grid size and constraints to minimize unnecessary calculations.
⚙️
Algorithm
3 steps- 1Step 1: Create a function to perform backtracking that tries to place stones in empty cells.
- 2Step 2: For each cell with excess stones, attempt to move stones to adjacent empty cells and recursively call the function.
- 3Step 3: Keep track of the number of moves and update the minimum moves found.
solution.py23 lines
1def minMoves(grid):
2 def backtrack(excess, empty, moves):
3 if not excess:
4 return moves
5 min_moves = float('inf')
6 x, y, count = excess[0]
7 for ex, ey in empty:
8 if abs(x - ex) + abs(y - ey) <= count:
9 new_excess = excess[1:]
10 new_empty = empty.copy()
11 new_empty.remove((ex, ey))
12 min_moves = min(min_moves, backtrack(new_excess, new_empty, moves + abs(x - ex) + abs(y - ey)))
13 return min_moves
14
15 excess = []
16 empty = []
17 for i in range(3):
18 for j in range(3):
19 if grid[i][j] > 1:
20 excess.append((i, j, grid[i][j] - 1))
21 elif grid[i][j] == 0:
22 empty.append((i, j))
23 return backtrack(excess, empty, 0)ℹ
Complexity note: The complexity is linear due to the limited number of cells (3x3), allowing efficient exploration of possible moves without excessive branching.
- 1The problem can be reduced to moving stones from overfilled to empty cells.
- 2The small grid size (3x3) allows for exhaustive search methods like backtracking.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.