Minimum Moves to Spread Stones Across a Grid
Problem statement
You are given a 3 x 3 integer grid. Each value is the number of stones currently in that cell, and the grid contains exactly 9 stones in total.
In one move, you may transfer one stone from a cell to an orthogonally adjacent cell. Return the minimum number of moves needed so that every cell contains exactly one stone.
Function
minimumMovesToSpreadStones(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0],[1,1,2],[1,1,1]]return = 1Move one stone from the center-right cell to the empty top-right cell.
Example 2
grid = [[1,3,0],[1,0,0],[1,0,3]]return = 4The four extra stones can be matched to the four empty cells with a total Manhattan distance of 4.
Example 3
grid = [[1,1,1],[1,1,1],[1,1,1]]return = 0Every cell already contains exactly one stone.
Constraints
grid.length = 3.grid[i].length = 3.0 <= grid[i][j] <= 9.- The sum of all values in
gridis exactly9.