Problem: Minimum Moves to Spread Stones Over Grid

You are given a 0-indexed 2D integer matrix `grid` of size `3 * 3`,
representing the number of stones in each cell. The grid contains exactly `9`
stones, and there can be multiple stones in a single cell.

In one move, you can move a single stone from its current cell to any other
cell if the two cells share a side.

Return the minimum number of moves required to place one stone in each cell.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def minimumMoves(self, grid: List[List[int]]) -> int:
    if sum(row.count(0) for row in grid) == 0:
      return 0

    ans = math.inf

    for i in range(3):
      for j in range(3):
        if grid[i][j] == 0:
          for x in range(3):
            for y in range(3):
              if grid[x][y] > 1:
                grid[x][y] -= 1
                grid[i][j] += 1
                ans = min(ans, abs(x - i) + abs(y - j) + self.minimumMoves(grid))
                grid[x][y] += 1
                grid[i][j] -= 1

    return ans


Java solution:
class Solution {
  public int minimumMoves(int[][] grid) {
    int zeroCount = 0;
    for (int[] row : grid)
      for (int cell : row)
        if (cell == 0)
          ++zeroCount;
    if (zeroCount == 0)
      return 0;

    int ans = Integer.MAX_VALUE;

    for (int i = 0; i < 3; ++i)
      for (int j = 0; j < 3; ++j)
        if (grid[i][j] == 0)
          for (int x = 0; x < 3; ++x)
            for (int y = 0; y < 3; ++y)
              if (grid[x][y] > 1) {
                --grid[x][y];
                ++grid[i][j];
                ans = Math.min(ans, Math.abs(x - i) + Math.abs(y - j) + minimumMoves(grid));
                ++grid[x][y];
                --grid[i][j];
              }

    return ans;
  }
}


C++ solution:
class Solution {
 public:
  int minimumMoves(vector<vector<int>>& grid) {
    const int zeroCount = accumulate(grid.begin(), grid.end(), 0,
                                     [](int acc, const vector<int>& row) {
      return acc + ranges::count(row, 0);
    });
    if (zeroCount == 0)
      return 0;

    int ans = INT_MAX;

    for (int i = 0; i < 3; ++i)
      for (int j = 0; j < 3; ++j)
        if (grid[i][j] == 0)
          for (int x = 0; x < 3; ++x)
            for (int y = 0; y < 3; ++y)
              // Move a stone at (x, y) to (i, j).
              if (grid[x][y] > 1) {
                --grid[x][y];
                ++grid[i][j];
                ans = min(ans, abs(x - i) + abs(y - j) + minimumMoves(grid));
                ++grid[x][y];
                --grid[i][j];
              }

    return ans;
  }
};