You are given a grid where each cell contains some number of stones. The total number of stones is exactly 9. However, some cells have 0 stones, and some have more than 1.
Your goal is to move the stones such that every cell has exactly 1 stone. In one move, you can move one stone from a cell to an adjacent cell (up, down, left, right). You want to find the minimum total moves required.
Microsoft and Google use this to test Permutations and Bipartite Matching (or simply Recursion/Backtracking). Key competencies:
The pattern is Backtracking (Permutations).
abs(r1 - r2) + abs(c1 - c2).Grid:
3 0 0
0 1 1
0 2 2
(0, 0): 2 stones to move. List: [(0,0), (0,0)].(2, 1): 1 stone. List: [(0,0), (0,0), (2,1)].(2, 2): 1 stone. List: [(0,0), (0,0), (2,1), (2,2)].(0, 1), (0, 2), (1, 0), (2, 0).
We need to pair the 4 extra stones with the 4 empty cells to minimize total Manhattan distance.When the input size is very small (like a grid), always consider "Brute Force with Recursion" or "Bitmask DP." These techniques are often simpler to implement and more robust than trying to find a clever greedy or flow-based solution.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| 01 Matrix | Medium | Solve | |
| As Far from Land as Possible | Medium | Solve | |
| Disconnect Path in a Binary Matrix by at Most One Flip | Medium | Solve | |
| Count Square Submatrices with All Ones | Medium | Solve | |
| Maximum Number of Points with Cost | Medium | Solve |