【Dijkstra】
class Solution {
public int minCost(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] dir = new int[][] { {0, 0}, {0, 1}, {0, -1}, {1, 0}, {-1, 0} };
int[][] dis = new int[m][n];
int inf = 1 << 30;
for(var i = 0; i < m; i++) Arrays.fill(dis[i], inf);
dis[0][0] = 0;
PriorityQueue<int[]> queue = new PriorityQueue<int[]>((a, b) -> {return a[0] - b[0];});
queue.offer(new int[] {0, 0, 0});
while(!queue.isEmpty()){
int[] top = queue.poll();
int d = top[0], x = top[1], y = top[2];
for(var i = 1; i < 5; i++){
int nx = x + dir[i][0], ny = y + dir[i][1];
if(nx >= 0 && nx < m && ny >= 0 && ny < n){
if(grid[x][y] == i){
if(d < dis[nx][ny]){
dis[nx][ny] = d;
queue.offer(new int[] {d, nx, ny});
}
}else{
if(d + 1 < dis[nx][ny]){
dis[nx][ny] = d + 1;
queue.offer(new int[] {dis[nx][ny], nx, ny});
}
}
}
}
}
return dis[m - 1][n - 1];
}
}