505. The Maze II

There is aballin a maze with empty spaces and walls. The ball can go through empty spaces by rollingup,down,leftorright, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

Given the ball'sstart position, thedestinationand themaze, find the shortest distance for the ball to stop at the destination. The distance is defined by the number ofempty spacestraveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.

The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.

tag: BFS

class Solution {
    public int shortestDistance(int[][] maze, int[] start, int[] destination) {
        if (maze == null || maze.length == 0) return -1;

        Queue<int[]> q = new LinkedList<>();
        int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int n = maze.length, m = maze[0].length;
        int[][] length = new int[n][m];
        for (int i = 0; i < n; i++){
            Arrays.fill(length[i], Integer.MAX_VALUE);
        }

        length[start[0]][start[1]] = 0;
        q.offer(new int[]{start[0], start[1], 0});

        int ans = Integer.MAX_VALUE;
        while (!q.isEmpty()){
            int[] cur = q.poll();
            if (cur[0] == destination[0] && cur[1] == destination[1]){
                ans = Math.min(ans, cur[2]);
            }

            for (int i = 0; i < 4; i++){
                int xx = cur[0] + dirs[i][0];
                int yy = cur[1] + dirs[i][1];

                if (xx < 0 || xx >= n || yy < 0 || yy >= m || maze[xx][yy] == 1) continue;
                int step = cur[2] + 1;

                while ( maze[xx][yy] != 1 ){
                    xx += dirs[i][0];
                    yy += dirs[i][1];
                    step++;

                    if (xx < 0 || xx >= n || yy < 0 || yy >= m) break;
                }

                xx -= dirs[i][0];
                yy -= dirs[i][1];
                step--;

                int[] temp = {xx, yy, step};

                if (length[xx][yy] < step) continue;


                length[xx][yy] = step;
                q.offer(temp);

                    //System.out.println("adding: " + " x: " + temp[0] + " y: " + temp[1] + " step: " + temp[2]);

            }
        }

        return ans == Integer.MAX_VALUE ? -1 : ans;
    }
}

results for ""

    No results matching ""