The Maze III

https://leetcode.com/problems/the-maze-iii/description/

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up (u), down (d), left (l) or right (r), but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls on to the hole.

Given the ball position, the hole position and the maze, find out how the ball could drop into the hole by moving the shortest distance. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the hole (included). Output the moving directions by using 'u', 'd', 'l' and 'r'. Since there could be several different shortest ways, you should output the lexicographically smallest way. If the ball cannot reach the hole, output "impossible".

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 ball and the hole coordinates are represented by row and column indexes.

Example 1

Input 1: a maze represented by a 2D array

0 0 0 0 0

1 1 0 0 1

0 0 0 0 0

0 1 0 0 1

0 1 0 0 0

Input 2: ball coordinate (rowBall, colBall) = (4, 3)

Input 3: hole coordinate (rowHole, colHole) = (0, 1)

Output: "lul"

Explanation: There are two shortest ways for the ball to drop into the hole.

The first way is left -> up -> left, represented by "lul".

The second way is up -> left, represented by 'ul'.

Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul".

Example 2

Input 1: a maze represented by a 2D array

0 0 0 0 0

1 1 0 0 1

0 0 0 0 0

0 1 0 0 1

0 1 0 0 0

Input 2: ball coordinate (rowBall, colBall) = (4, 3)

Input 3: hole coordinate (rowHole, colHole) = (3, 0)

Output: "impossible"

Explanation: The ball cannot reach the hole.

Note:

There is only one ball and one hole in the maze.

Both the ball and hole exist on an empty space, and they will not be at the same position initially.

The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.

The maze contains at least 2 empty spaces, and the width and the height of the maze won't exceed 30.

Thoughts

二维矩阵,0代表能走,1代表不能,给定起点和终点,每次走会一直顺着指定方向滚下去直到撞到1,问从起点到终点最短距离(以格子为单位)是什么,而且必须同时是指令的lexicographical最先。图上两点最短BFS。每次按方向一直滚下去并把滚过来的指令和dist记录下来;如果比已有的少就压入队列继续遍历。和普通BFS不同的是不能因为以前访问过就排除,因为访问过只是说明BFS level少,但可能滚动的距离远。最后等Q为空时停下来。每个结点虽然可能会被多次访问,但同一个方向不太可能再遍历一次且比之前的距离小,因此总时间不会太长。

Code

class Solution {
public:
    string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
        const int M = maze.size(), N = maze[0].size();
        vector<vector<int>> dirs({{-1, 0, (int)'u'}, {1, 0, (int)'d'}, {0, -1, (int)'l'}, {0, 1, (int)'r'}});
        vector<vector<int>> dist(M, vector<int>(N, INT_MAX));
        vector<vector<string>> routes(M, vector<string>(N));
        queue<vector<int>> q;
        dist[ball[0]][ball[1]] = 0;
        q.push(ball);
        while (!q.empty()) {
            for (int i = q.size() - 1; i >= 0; --i) {
                const auto &t = q.top();
                const auto d = dist[t[0]][t[1]];
                const auto r = routes[t[0]][t[1]];
                for (const auto &dir : dirs) {
                    const auto x = t[0] + dir[0];
                    const auto y = t[1] + dir[1];
                    int cd = d + 1;
                    while (x >= 0 && x < M && y >= 0 && y < N && maze[x][y] == 0 && (x != hole[0] || y != hole[1])) {
                        ++cd;
                    }
                    if (x != hole[0] || y != hole[1]) {
                        x -= dir[0];
                        y -= dir[1];
                        --cd;
                        // 不能因为以前访问过就排除,因为访问过只是BFS level少,但可能滚动的距离远。
                        if (cd < dist[x][y] || dist[x][y] == cd && routes[x][y].compare(r + dir[2]) > 0) {
                            q.push({x, y});
                        }
                    }
                    if (dist[x][y] > cd) {
                        dist[x][y] = cd;
                        routes[x][y] = route + dir[2];
                    } else if (dist[x][y] == cd && routes[x][y].compare(r + dir[2]) > 0) {
                        routes[x][y] = route + dir[2];
                    }
                }
                q.pop();
            }
        }
        return dist[hole[0]][hole[1]] == INT_MAX ? "impossible" : routes[hole[0]][hole[1]];
    }
};
class Solution {
    public String findShortestWay(int[][] maze, int[] start, int[] hole) {
        int m = maze.length, n = m == 0 ? 0 : maze[0].length;
        int[][] dirs = new int[][]{{-1, 0, (int)'u'}, {1, 0, (int)'d'}, {0, -1, (int)'l'}, {0, 1, (int)'r'}};
        int[][] dists = new int[m][n];
        String[][] routes = new String[m][n];
        for (int i = 0; i < m * n; i++) {
            dists[i / n][i % n] = Integer.MAX_VALUE;
            routes[i / n][i % n] = "";
        }
        Queue<int[]> queue = new LinkedList<>();
        dists[start[0]][start[1]] = 0;
        queue.offer(start);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] pos = queue.poll();
                int dist = dists[pos[0]][pos[1]];
                String route = routes[pos[0]][pos[1]];
                for (int[] dir : dirs) {
                    int ndist = dist + 1;
                    int x = pos[0] + dir[0];
                    int y = pos[1] + dir[1];
                    while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0 && (x != hole[0] || y != hole[1])) {
                        x += dir[0];
                        y += dir[1];
                        ndist++;
                    }
                    if (x != hole[0] || y != hole[1]) {
                        x -= dir[0];
                        y -= dir[1];
                        ndist--;
                        if (dists[x][y] > ndist || dists[x][y] == ndist && (route + (char)dir[2]).compareTo(routes[x][y]) < 0) {
                            queue.offer(new int[]{x, y});
                        }
                    }
                    if (dists[x][y] > ndist) {
                        dists[x][y] = ndist;
                        routes[x][y] = route + (char)dir[2];
                    } else if (dists[x][y] == ndist && (route + (char)dir[2]).compareTo(routes[x][y]) < 0) {
                        routes[x][y] = route + (char)dir[2];
                    }
                }
            }
        }
        return dists[hole[0]][hole[1]] == Integer.MAX_VALUE ? "impossible" : routes[hole[0]][hole[1]];
    }
}

Analysis

Last updated