2850. Minimum Moves to Spread Stones Over Grid
class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
zeros=[]
excesses=[]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==0:
zeros.append((i,j))
elif grid[i][j]>1:
excesses.append((i,j))
ans=-1
def back(steps,index):
nonlocal ans
if index==len(zeros):
ans=min(ans,steps)if ans!=-1 else steps
for (i,j) in excesses:
if grid[i][j]>1:
grid[i][j]-=1
step=abs(i-zeros[index][0])+abs(j-zeros[index][1])
back(steps+step,index+1)
grid[i][j]+=1
back(0,0)
return ans
回溯写法比较简单,贪心不一定正确