LeetCode 1368. 使网格图至少有一条有效路径的最小代价

1368. 使网格图至少有一条有效路径的最小代价

 

【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];
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值