Ctrl K

Stones on a 3 × 3 Board

Medium
Exactly 9 stones lie on a 3 × 3 board: board[i][j] is the number of stones in cell (i, j). A cell may hold several stones, and some cells may be empty. In one move you pick up a single stone and put it into a cell that shares a side with its current one. Return the minimum number of moves after which every cell holds exactly one stone.
Example 1
board=[[0, 2, 1], [1, 1, 1], [1, 1, 1]] → 1

Slide the spare stone from the top middle cell one step left: 1 move.

Example 2
board=[[3, 0, 0], [0, 3, 0], [0, 0, 3]] → 8

The spare stones of the two corners fill their four neighbours in 4 moves, and the centre's two spare stones travel to the two empty corners, 2 moves each. Total 8.

Example 3
board=[[1, 1, 1], [1, 1, 1], [1, 1, 1]] → 0

Every cell already holds one stone, so no moves are needed.

Constraints
  • board is a 3 × 3 matrix
  • 0 ≤ board[i][j] ≤ 9
  • All board[i][j] add up to 9
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSteps to the Nearest Zero MediumFarthest From Any Shore MediumBlock the Only Route MediumLongest Uphill Walk HardSix-Cell Tile Slider Hard
loading Python…
Input
board=[[0, 2, 1], [1, 1, 1], [1, 1, 1]]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 29 tests on the server, hidden ones included.