There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, 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 onto the hole.
Given the m x n maze, the ball's position ball and the hole's position hole, where ball = [ballrow, ballcol] and hole = [holerow, holecol], return a string instructions of all the instructions that the ball should follow to drop in the hole with the shortest distance possible. If there are multiple valid instructions, return the lexicographically minimum one. If the ball can't drop in the hole, return "impossible".
If there is a way for the ball to drop in the hole, the answer instructions should contain the characters 'u' (i.e., up), 'd' (i.e., down), 'l' (i.e., left), and 'r' (i.e., right).
The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included).
You may assume that the borders of the maze are all walls (see examples).
Example 1
Input: maze = [[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]], ball = [4,3], hole = [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".
Constraints:
m == maze.lengthn == maze[i].length1 <= m, n <= 100maze[i][j]is0or1.ball.length == 2hole.length == 20 <= ballrow, holerow <= m0 <= ballcol, holecol <= m- Both the ball and the hole exist in an empty space, and they will not be in the same position initially.
- The maze contains at least 2 empty spaces.
- This question is again an upgrade of a previous one.
- The difference is not only we have to find the route with shorest distance, also we need to find the lexicographically smallest one.
- However, with the confidence and experience so far with the maze, we should have a good idea already.
- So previously we had a
distarray to record the shortest distances for each cell, and now we have to find the lexicographically smallest route with all the instructions ('d','l','r','u'). - "So BFS?", you might ask? Actually it's not the best solution. But it's definitely a viable solution. Let's see why.
- We already know we need to update the distance for each cell every time we find a shorter one. Especially, we need to remember to update for the target cell
hole. But that's not all, because, we also need to update the current best route (instructions to get to thehole). - However, what about when we found a different route with the same distance as current shortest distance? You're right, we might have to update the shortest route too, because it might be "lexicographically" smaller (this one is very important and easy to miss, without this logic, you probably won't get the right answer).
- BTW, there's a slight difference when we need to update the distance and route, based on if we reach the wall or the
hole, which is, we enqueue only when we will reach the wall. Because if we reach the hole, we find a valid solution, and following that instructions won't find a better solution than the current one. Also you can think of it dropping into the hole, so no need to enqueue following instructions. - Also another small edge case is that we the ball is next to the wall, for example, it's above the wall and next to it, then if we move downwards, it won't go anywhere, so in the case we won't add
'd'to our instructions, because 1) this instruction does not move the ball, 2) if this is valid, you could generate an infinitely lexicographically smallest instructions likeddddddddddddd.... Oh my, that's not what we want. - "Hey, this is not too bad, why you are saying it's not the best solution?", you might ask.
- That's an excellent question, as always.
- I would say it's still a good solution, so nothing wrong about it. Normally when we choose BFS, it's because we want to find the shortest solution (path, route, instruction, whatever), we are trying to utilize the fact that we traverse equally fast for all cells on the same level, in that case, when we reach our destination, we can guarantee that it's the shortest solution.
- However, for this question, we need the lexicographically smallest one, that means, we need to find basically all solutions and compare them and find the lexicographically smallest one, simply because if you don't find all the solutions, you won't rest assured that you found the best one.
- So that's the hint to a slightly-easier-to-write solution, which is DFS. An advantage of DFS is we recursively call this function and it'll solve our issue, almost, magically. Think of it like this, we start from our start
ballcell, we try all the directions (in the order of'd','l','r','u'), and as we walk we collect the distance and the route, whenever we reach thehole, we compare with current best instruction, we update the solution only if we find a shorter instruction. Because it's equal to current best, then it's lexicographically larger, since we are doing it in the order of'd','l','r','u'on purpose. - Another small benefit of DFS here is since we record the instructions while we walk, there's no need to have a separate array for it. So very neat. As you can see, the DFS code is much shorter than the BFS one.
- Thanks for your time reading. The code now should be easy enough to understand, let me know if you think otherwise.
function findShortestWay(maze, ball, hole) {
const R = maze.length, C = maze[0].length;
const DIRS = [[1,0,'d'],[0,-1,'l'],[0,1,'r'],[-1,0,'u']];
const [startX, startY] = ball, [endX, endY] = hole;
const dist = Array(R).fill(0).map(_ => Array(C).fill(Infinity));
dist[startX][startY] = 0;
// 'x' > 'u' and means 'not reachable'
const route = Array(R).fill(0).map(_ => Array(C).fill('x'));
const queue = [[startX, startY, 0, '']]; // [x, y, steps, curInstr]
bfs();
if (dist[endX][endY] == Infinity) return 'impossible';
return route[endX][endY];
function bfs() {
while (queue.length) {
const [x, y, d, instr] = queue.shift();
if (dist[x][y] < d) continue;
for (const [dx, dy, dir] of DIRS) {
const [nx, ny, stepsToWall, stepsToHole] = walk(x, y, dx, dy);
const curInstr = (nx == x && ny == y) ? instr : instr + dir;
if (stepsToHole > 0) {
updateDistAndRoute(x, y, endX, endY, stepsToHole, curInstr, false);
} else {
updateDistAndRoute(x, y, nx, ny, stepsToWall, curInstr, true);
}
}
}
}
function updateDistAndRoute(x, y, nx, ny, steps, instr, isWall) {
if (dist[x][y] + steps < dist[nx][ny] ||
(dist[x][y] + steps == dist[nx][ny] && instr < route[nx][ny])) {
dist[nx][ny] = dist[x][y] + steps;
route[nx][ny] = instr;
if (isWall) queue.push([nx, ny, dist[nx][ny], instr]);
}
}
function walk(x, y, dx, dy) {
let curSteps = 0, stepsToHole = 0;
while (x >= 0 && y >= 0 && x < R && y < C && !maze[x][y]) {
if (x == endX && y == endY) stepsToHole = curSteps;
x += dx, y += dy;
curSteps += 1;
}
return [x - dx, y - dy, curSteps - 1, stepsToHole];
}
}function findShortestWay(maze, ball, hole) {
const R = maze.length, C = maze[0].length;
const [targetR, targetC] = hole;
const isValid = (r, c) => (r >= 0 && r < R && c >= 0 && c < C && !maze[r][c]);
const DIRS = [[1,0,"d"],[0,-1,"l"],[0,1,"r"],[-1,0,"u"]];
const costs = [...Array(R)].map(_ => Array(C).fill(Infinity));
let minRoute = "";
dfs(ball[0], ball[1], 0, "");
return minRoute || "impossible";
function dfs(row, col, cost, route) {
if (cost >= costs[row][col]) return;
costs[row][col] = cost;
for (const [dr, dc, dir] of DIRS) {
let r = row, c = col, steps = 0;
while (isValid(r+dr, c+dc)) {
r += dr, c += dc, steps += 1;
if (r == targetR && c == targetC) {
if (cost + steps < costs[targetR][targetC]) {
costs[targetR][targetC] = cost + steps;
minRoute = route + dir;
}
return;
}
}
dfs(r, c, cost + steps, route + dir);
}
}
}