Loading...
You are given a 3 x 3 integer matrix grid where grid[i][j] is the number of units in cell (i, j). The grid holds exactly 9 units in total; a cell may hold several units or none.
In one move you may transfer a single unit from a cell to a side-adjacent cell.
Return the minimum number of moves needed to reach a state where every cell holds exactly one unit.
Input: grid = [[1,1,0],[1,1,1],[1,2,1]]
Output: 3
Explanation: The extra unit at (2,1) travels (2,1) -> (2,2) -> (1,2) -> (0,2): three moves.
Input: grid = [[1,3,0],[1,0,0],[1,0,3]]
Output: 4
Explanation: From (0,1) send one unit to (0,2) and one to (1,1); from (2,2) send one to (1,2) and one to (2,1). Four moves in total.
grid.length == grid[i].length == 3grid[i][j] ≤99Click "Run" to test with sample cases or "Submit" to run all tests.