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.

Example 1
1 1 0
1 1 1
1 2 1
Inputgrid = [[1,1,0],[1,1,1],[1,2,1]]
Output3
In total, it takes 3 moves to place one stone in each cell of the grid, and 3 is the minimum number of moves required.
Example 2
1 3 0
1 0 0
1 0 3
Inputgrid = [[1,3,0],[1,0,0],[1,0,3]]
Output4
In total, it takes 4 moves to place one stone in each cell of the grid, and 4 is the minimum number of moves required.

Constraints

  • grid.length == grid[i].length == 3
  • 0 <= grid[i][j] <= 9
  • Sum of grid is equal to 9.

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate