Given a 2D grid of integers of size (
Constraints:
Only one stone can be moved in one move.
Stone from a cell can only be moved to another cell if they are adjacent (share a side).
The sum of all stones in the grid must be equal to
grid.length, grid[i].length
grid[i][j]
This solution works by trying different combinations of moving extra stones around the grid until each empty cell has at least one stone.
First, we check if there are exactly
If a cell is empty, we mark down its position.
If a cell has more than one stone, we note its position and the number of extra stones.
Once we know the locations of the empty cells and the cells with extra stones, we start exploring possible moves. We try placing each extra stone into each empty cell, one by one, and calculate the moves needed for each trial. The number of moves to transfer a stone from the extra cell at position
Given a 2D grid of integers of size (
Constraints:
Only one stone can be moved in one move.
Stone from a cell can only be moved to another cell if they are adjacent (share a side).
The sum of all stones in the grid must be equal to
grid.length, grid[i].length
grid[i][j]
This solution works by trying different combinations of moving extra stones around the grid until each empty cell has at least one stone.
First, we check if there are exactly
If a cell is empty, we mark down its position.
If a cell has more than one stone, we note its position and the number of extra stones.
Once we know the locations of the empty cells and the cells with extra stones, we start exploring possible moves. We try placing each extra stone into each empty cell, one by one, and calculate the moves needed for each trial. The number of moves to transfer a stone from the extra cell at position