LeetCode LCP 56. 信物传送

LCP 56. 信物传送

LeetCode LCP 56. 信物传送_第1张图片 LeetCode LCP 56. 信物传送_第2张图片

 【Dijkstra】

class Solution {
    public int conveyorBelt(String[] matrix, int[] start, int[] end) {
        int m = matrix.length, n = matrix[0].length();
        int[][] dis = new int[m][n];
        int inf = 1 << 30;
        for(var i = 0; i < m; i++) Arrays.fill(dis[i], inf);
        dis[start[0]][start[1]] = 0;
        int[][] dir = new int[][] { {0, 1}, {0, -1}, {-1, 0}, {1, 0} };
        char[] cc = new char[] {'>', '<', '^', 'v'};
        Map map = new HashMap();
        for(var i = 0; i < 4; i++) map.put(cc[i], i);
        PriorityQueue queue = new PriorityQueue((a, b) -> { return a[0]- b[0]; });
        queue.offer(new int[] {0, start[0], start[1]});
        while(!queue.isEmpty()){
            var top = queue.poll();
            int d = top[0], x = top[1], y = top[2];
            // System.out.println(d + ", " + x + " " + y);
            if(x == end[0] && y == end[1]) return d;
            char c = matrix[x].charAt(y);
            int j = map.get(c);
            for(var i = 0; i < 4; i++){
                int nx = x + dir[i][0];
                int ny = y + dir[i][1];
                if(nx >= 0 && nx < m && ny >= 0 && ny < n){
                    if(i == j){
                        if(d < dis[nx][ny]) {
                            dis[nx][ny] = d;
                            queue.offer(new int[] {dis[nx][ny], 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[end[0]][end[1]];
    }
}

你可能感兴趣的:(LeetCode,leetcode,Dijkstra)