Minimum Moves to Spread Stones Over Grid

3×3 grid with 9 stones across cells (some empty, some doubled) — backtrack to match donors and receivers by min Manhattan distance.

Medium
Time O((k!)^2) Space O(k)
LeetCode
5 min read
backtracking

Problem#

3×3 grid with 9 total stones (some cells empty, others have ≥1). One move shifts a stone to an adjacent cell. Minimum moves so each cell has exactly 1 stone.

Examples#

  • grid = [[1,1,0],[1,1,1],[1,2,1]]3

Constraints#

  • Sum of grid values is 9.

Approach#

Collect “donors” (cells with count > 1, with multiplicity = count - 1) and “receivers” (cells with count == 0). Try all assignments of donors to receivers; cost = Manhattan distance per pair. Backtrack over permutations.

Solution#

Spread Stones (backtrack)
class Solution {
public:
int minimumMoves(vector<vector<int>>& grid) {
vector<pair<int,int>> donors, receivers;
for (int r = 0; r < 3; ++r) for (int c = 0; c < 3; ++c) {
if (grid[r][c] > 1) for (int k = 0; k < grid[r][c] - 1; ++k) donors.push_back({r, c});
else if (grid[r][c] == 0) receivers.push_back({r, c});
}
sort(donors.begin(), donors.end());
int best = INT_MAX;
do {
int cost = 0;
for (int i = 0; i < (int)donors.size(); ++i) {
cost += abs(donors[i].first - receivers[i].first)
+ abs(donors[i].second - receivers[i].second);
}
best = min(best, cost);
} while (next_permutation(donors.begin(), donors.end()));
return best;
}
};

Editorial#

3×3 grid bounds donors ≤ 9. next_permutation enumerates all donor orderings; each pairs with the fixed receiver order. Total < 9! = 362880 permutations — easily tractable.

Complexity#

  • Time: O(k! × k) where k = #donors ≤ 9.
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.