Facebook
From Thundering Mousedeer, 4 Years ago, written in Plain Text.
This paste is a reply to Re: Untitled from Speedy Pintail - go back
Embed
Viewing differences between Re: Untitled and Re: Re: Untitled
class Solution {
    public boolean hasPath(int[][] int shortestDistance(int[][] maze, int[] start, int[] destination) {
        int nr = maze.length;
        int nc = maze[0].length;
        boolean[][] visited int[][] distances = new boolean[nr][nc];
        
int[nr][nc];
        for (int[] row : distances) {
            Arrays.fill(row, Integer.MAX_VALUE);
        }
        
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 0}};
        Queue queue = new LinkedList<>();
        queue.add(start);
        visited[start[0]][start[1]] = true;\n        while (!queue.isEmpty()) {
            int[] idx curr = queue.poll();
            if (idx[0] == destination[0] && idx[1] == destination[1]) {\n                return true;\n            }\n            for (int[] dir : dirs) {
                int x = idx[0] curr[0] + dir[0];
                int y = idx[1] curr[1] + dir[1];
                int count = 0;
                
while (x >= 0 && x < nr &&
                      
y >= 0 && x < nr && y < nc &&
                      maze[x][y] == 0) != 1) {
                    x += dir[0];
                    y += dir[1];
                    count++;
                }
                if (!visited[x - dir[0]][y - dir[1]]) {
(distances[curr[0]][curr[1]] + count < distances[x-dir[0]][y-dir[1]]) {
                    distances[x-dir[0]][y-dir[1]] = distances[curr[0]][curr[1]] + count;
                    queue.add(new int[] {x int[]{x - dir[0], y - dir[1]});
                    visited[x - dir[0]][y - dir[1]] = true;
dir[1]});
                }
            }
        }
        return false;
distances[destination[0]][destination[1]] == Integer.MAX_VALUE ? -1 : distances[destination[0]][destination[1]];
    }
}