FastPrepMinimum Moves to Spread Stones Across a Grid

Minimum Moves to Spread Stones Across a Grid

American Express logoAmerican Express● MediumINTERNOA
Learn

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[][]) → int

Examples

Example 1

grid = [[1,1,0],[1,1,2],[1,1,1]]return = 1

Move 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 = 4

The 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 = 0

Every 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 grid is exactly 9.

More American Express problems

See American Express hiring insights
public int minimumMovesToSpreadStones(int[][] grid) {
    // write your code here
}
grid[[1,1,0],[1,1,2],[1,1,1]]
expected1
Checking account…