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 theminimum number of moves required to place one stone in each cell.

Input: grid =[[1,1,0],[1,1,1],[1,2,1]]Output: 3Explanation: One possible sequence of moves to place one stone in each cell is:1- Move one stone from cell(2,1) to cell(2,2).2- Move one stone from cell(2,2) to cell(1,2).3- Move one stone from cell(1,2) to cell(0,2).In total, it takes 3 moves to place one stone in each cell of the grid.It can be shown that 3is the minimum number of moves required to place one stone in each cell.

Input: grid =[[1,3,0],[1,0,0],[1,0,3]]Output: 4Explanation: One possible sequence of moves to place one stone in each cell is:1- Move one stone from cell(0,1) to cell(0,2).2- Move one stone from cell(0,1) to cell(1,1).3- Move one stone from cell(2,2) to cell(1,2).4- Move one stone from cell(2,2) to cell(2,1).In total, it takes 4 moves to place one stone in each cell of the grid.It can be shown that 4is the minimum number of moves required to place one stone in each cell.
Each cell must end up with exactly one stone. We encode the grid state and use BFS to explore all possible moves, always moving a stone from a cell with excess to a cell with deficit, and track the minimum moves.
classSolution {
funminimumMoves(grid: Array<IntArray>): Int {
val vis = mutableSetOf<String>()
val q = ArrayDeque<Pair<Array<IntArray>, Int>>()
q.add(grid.map { it.clone() }.toTypedArray() to 0)
vis.add(encode(grid))
while (q.isNotEmpty()) {
val(g, moves) = q.removeFirst()
if (done(g)) return moves
for (i in0..2) {
for (j in0..2) {
if (g[i][j] > 1) {
for ((dx, dy) in listOf(0 to 1, 0 to -1, 1 to 0, -1 to 0)) {
val ni = i+dx; val nj = j+dy
if (ni in0..2&& nj in0..2&& g[ni][nj]<1) {
val ng = g.map { it.clone() }.toTypedArray()
ng[i][j]-- ng[ni][nj]++val key = encode(ng)
if (key !in vis) {
vis.add(key)
q.add(ng to moves+1)
}
}
}
}
}
}
}
return -1 }
privatefundone(g: Array<IntArray>) = g.all { it.all { v -> v ==1 } }
privatefunencode(g: Array<IntArray>) = g.joinToString("-") { it.joinToString(",") }
}
classSolution:
defminimumMoves(self, grid: list[list[int]]) -> int:
from collections import deque
defencode(g: list[list[int]]) -> tuple:
return tuple(tuple(row) for row in g)
defdone(g: list[list[int]]) -> bool:
return all(g[i][j]==1for i in range(3) for j in range(3))
vis = set()
q = deque([(grid, 0)])
vis.add(encode(grid))
while q:
g, moves = q.popleft()
if done(g): return moves
for i in range(3):
for j in range(3):
if g[i][j] >1:
for dx, dy in [(0,1),(0,-1),(1,0),(-1,0)]:
ni, nj = i+dx, j+dy
if0<=ni<3and0<=nj<3and g[ni][nj]<1:
ng = [row[:] for row in g]
ng[i][j] -=1 ng[ni][nj] +=1 key = encode(ng)
if key notin vis:
vis.add(key)
q.append((ng, moves+1))
return-1