DIRS =[(0,1),(0,-1),(1,0),(-1,0)]classSolution:defminCost(self, grid: List[List[int]])->int:
m,n =len(grid),len(grid[0])definside(x,y):return0<=x<m and0<=y<n
dist =[[inf]*n for _ inrange(m)]
dist[0][0]=0
q = deque([(0,0,0)])while q:
c,x,y = q.popleft()if x == m-1and y == n-1:return c
if c > dist[x][y]:continuefor i,(dx,dy)inenumerate(DIRS,1):
a,b = x+dx,y+dy
if inside(a,b):
w =int(grid[x][y]!= i)
d = c + w
if d < dist[a][b]:
dist[a][b]= d
if w>0:
q.append((d,a,b))else:
q.appendleft((d,a,b))return-1