# 499. The Maze III

## Description

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".


Example 2:

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 = [3,0]
Output: "impossible"
Explanation: The ball cannot reach the hole.


Example 3:

Input: maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5]
Output: "dldr"


Constraints:

• m == maze.length
• n == maze[i].length
• 1 <= m, n <= 100
• maze[i][j] is 0 or 1.
• ball.length == 2
• hole.length == 2
• 0 <= ballrow, holerow <= m
• 0 <= ballcol, holecol <= n
• 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.

## Solutions

BFS.

• class Solution {
public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
int m = maze.length;
int n = maze[0].length;
int r = ball[0], c = ball[1];
int rh = hole[0], ch = hole[1];
q.offer(new int[] {r, c});
int[][] dist = new int[m][n];
for (int i = 0; i < m; ++i) {
Arrays.fill(dist[i], Integer.MAX_VALUE);
}
dist[r][c] = 0;
String[][] path = new String[m][n];
path[r][c] = "";
int[][] dirs = { {-1, 0, 'u'}, {1, 0, 'd'}, {0, -1, 'l'}, {0, 1, 'r'} };
while (!q.isEmpty()) {
int[] p = q.poll();
int i = p[0], j = p[1];
for (int[] dir : dirs) {
int a = dir[0], b = dir[1];
String d = String.valueOf((char) (dir[2]));
int x = i, y = j;
int step = dist[i][j];
while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0
&& (x != rh || y != ch)) {
x += a;
y += b;
++step;
}
if (dist[x][y] > step
|| (dist[x][y] == step && (path[i][j] + d).compareTo(path[x][y]) < 0)) {
dist[x][y] = step;
path[x][y] = path[i][j] + d;
if (x != rh || y != ch) {
q.offer(new int[] {x, y});
}
}
}
}
return path[rh][ch] == null ? "impossible" : path[rh][ch];
}
}

• class Solution {
public:
string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
int m = maze.size();
int n = maze[0].size();
int r = ball[0], c = ball[1];
int rh = hole[0], ch = hole[1];
queue<pair<int, int>> q;
q.push({r, c});
vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
dist[r][c] = 0;
vector<vector<string>> path(m, vector<string>(n, ""));
vector<vector<int>> dirs = { {-1, 0, 'u'}, {1, 0, 'd'}, {0, -1, 'l'}, {0, 1, 'r'} };
while (!q.empty()) {
auto p = q.front();
q.pop();
int i = p.first, j = p.second;
for (auto& dir : dirs) {
int a = dir[0], b = dir[1];
char d = (char) dir[2];
int x = i, y = j;
int step = dist[i][j];
while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0 && (x != rh || y != ch)) {
x += a;
y += b;
++step;
}
if (dist[x][y] > step || (dist[x][y] == step && (path[i][j] + d < path[x][y]))) {
dist[x][y] = step;
path[x][y] = path[i][j] + d;
if (x != rh || y != ch) q.push({x, y});
}
}
}
return path[rh][ch] == "" ? "impossible" : path[rh][ch];
}
};

• class Solution:
def findShortestWay(
self, maze: List[List[int]], ball: List[int], hole: List[int]
) -> str:
m, n = len(maze), len(maze[0])
r, c = ball
rh, ch = hole
q = deque([(r, c)])
dist = [[inf] * n for _ in range(m)]
dist[r][c] = 0
path = [[None] * n for _ in range(m)]
path[r][c] = ''
while q:
i, j = q.popleft()
for a, b, d in [(-1, 0, 'u'), (1, 0, 'd'), (0, -1, 'l'), (0, 1, 'r')]:
x, y, step = i, j, dist[i][j]
while (
0 <= x + a < m
and 0 <= y + b < n
and maze[x + a][y + b] == 0
and (x != rh or y != ch)
):
x, y = x + a, y + b
step += 1
if dist[x][y] > step or (
dist[x][y] == step and path[i][j] + d < path[x][y]
):
dist[x][y] = step
path[x][y] = path[i][j] + d
if x != rh or y != ch:
q.append((x, y))
return path[rh][ch] or 'impossible'


• import "math"

func findShortestWay(maze [][]int, ball []int, hole []int) string {
m, n := len(maze), len(maze[0])
r, c := ball[0], ball[1]
rh, ch := hole[0], hole[1]
q := [][]int{[]int{r, c} }
dist := make([][]int, m)
path := make([][]string, m)
for i := range dist {
dist[i] = make([]int, n)
path[i] = make([]string, n)
for j := range dist[i] {
dist[i][j] = math.MaxInt32
path[i][j] = ""
}
}
dist[r][c] = 0
dirs := map[string][]int{"u": {-1, 0}, "d": {1, 0}, "l": {0, -1}, "r": {0, 1} }
for len(q) > 0 {
p := q[0]
q = q[1:]
i, j := p[0], p[1]
for d, dir := range dirs {
a, b := dir[0], dir[1]
x, y := i, j
step := dist[i][j]
for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 && (x != rh || y != ch) {
x += a
y += b
step++
}
if dist[x][y] > step || (dist[x][y] == step && (path[i][j]+d) < path[x][y]) {
dist[x][y] = step
path[x][y] = path[i][j] + d
if x != rh || y != ch {
q = append(q, []int{x, y})
}
}
}
}
if path[rh][ch] == "" {
return "impossible"
}
return path[rh][ch]
}