499. The Maze III
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
This problem asks for the shortest path from a starting ball position to a hole in a maze. The path's length is the number of cells traveled. If multiple paths have the same shortest distance, we need the one with the lexicographically smallest instruction string (e.g., "d", "l", "r", "u").
Solution
The Maze III in Python
import heapq
class Solution:
def findShortestWay(self, maze: List[List[int]], ball: List[int], hole: List[int]) -> str:
m, n = len(maze), len(maze[0])
hole = tuple(hole)
# dist_path stores {distance, path_string} for each reachable stopping point
dist_path = {(ball[0], ball[1]): (0, "")}
# Priority queue stores (distance, path_string, row, col)
# Python's heapq with tuples provides the required lexicographical sorting
pq = [(0, "", ball[0], ball[1])]
# Directions: d, l, r, u (for lexicographical order of path)
dirs = {'d': (1, 0), 'l': (0, -1), 'r': (0, 1), 'u': (-1, 0)}
while pq:
d, path, r, c = heapq.heappop(pq)
# If we found a better path already, skip
if (d, path) > dist_path.get((r, c), (float('inf'), '')):
continue
# If we extract the hole, we are done because Dijkstra's finds shortest path first.
# The first time we pop the hole, it's guaranteed to be the best path.
if (r, c) == hole:
return path
for dir_char in "dlru":
dr, dc = dirs[dir_char]
curr_r, curr_c = r, c
steps = 0
# Roll the ball
while True:
next_r, next_c = curr_r + dr, curr_c + dc
# Check for wall or boundary
if not (0 <= next_r < m and 0 <= next_c < n and maze[next_r][next_c] == 0):
# Ball stops at (curr_r, curr_c)
if steps > 0:
new_dist = d + steps
new_path = path + dir_char
stop_pos = (curr_r, curr_c)
if (new_dist, new_path) < dist_path.get(stop_pos, (float('inf'), '')):
dist_path[stop_pos] = (new_dist, new_path)
heapq.heappush(pq, (new_dist, new_path, curr_r, curr_c))
break # Stop rolling in this direction
curr_r, curr_c = next_r, next_c
steps += 1
# Check if ball passes through the hole
if (curr_r, curr_c) == hole:
new_dist = d + steps
new_path = path + dir_char
if (new_dist, new_path) < dist_path.get(hole, (float('inf'), '')):
dist_path[hole] = (new_dist, new_path)
heapq.heappush(pq, (new_dist, new_path, hole[0], hole[1]))
break # Stop rolling, ball fell in hole
return "impossible"
The Maze III in Java
class Solution {
public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
int m = maze.length;
int n = maze[0].length;
PointInfo[][] distPath = new PointInfo[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
distPath[i][j] = new PointInfo(Integer.MAX_VALUE, "");
}
}
PriorityQueue<State> pq = new PriorityQueue<>((a, b) -> {
if (a.dist != b.dist) {
return a.dist - b.dist;
}
return a.path.compareTo(b.path);
});
distPath[ball[0]][ball[1]].dist = 0;
pq.offer(new State(0, "", ball[0], ball[1]));
int[][] dirs = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
char[] dirChars = {'d', 'l', 'r', 'u'};
while (!pq.isEmpty()) {
State current = pq.poll();
int d = current.dist;
String path = current.path;
int r = current.r;
int c = current.c;
if (d > distPath[r][c].dist || (d == distPath[r][c].dist && path.compareTo(distPath[r][c].path) > 0)) {
continue;
}
if (r == hole[0] && c == hole[1]) {
return path;
}
for (int i = 0; i < 4; i++) {
int dr = dirs[i][0];
int dc = dirs[i][1];
char dirChar = dirChars[i];
int currR = r;
int currC = c;
int steps = 0;
while (true) {
int nextR = currR + dr;
int nextC = currC + dc;
if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n || maze[nextR][nextC] == 1) {
// Hit a wall or boundary, ball stops at (currR, currC)
if (steps > 0) {
int newDist = d + steps;
String newPath = path + dirChar;
if (newDist < distPath[currR][currC].dist ||
(newDist == distPath[currR][currC].dist && newPath.compareTo(distPath[currR][currC].path) < 0)) {
distPath[currR][currC] = new PointInfo(newDist, newPath);
pq.offer(new State(newDist, newPath, currR, currC));
}
}
break; // Stop rolling in this direction
}
currR = nextR;
currC = nextC;
steps++;
if (currR == hole[0] && currC == hole[1]) {
// Passed through the hole
int newDist = d + steps;
String newPath = path + dirChar;
if (newDist < distPath[hole[0]][hole[1]].dist ||
(newDist == distPath[hole[0]][hole[1]].dist && newPath.compareTo(distPath[hole[0]][hole[1]].path) < 0)) {
distPath[hole[0]][hole[1]] = new PointInfo(newDist, newPath);
pq.offer(new State(newDist, newPath, hole[0], hole[1]));
}
break; // Ball falls in, stop rolling
}
}
}
}
return distPath[hole[0]][hole[1]].dist == Integer.MAX_VALUE ? "impossible" : distPath[hole[0]][hole[1]].path;
}
}
class PointInfo {
int dist;
String path;
PointInfo(int dist, String path) {
this.dist = dist;
this.path = path;
}
}
class State {
int dist;
String path;
int r, c;
State(int dist, String path, int r, int c) {
this.dist = dist;
this.path = path;
this.r = r;
this.c = c;
}
}
The Maze III in C++
class Solution {
public:
string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
int m = maze.size();
int n = maze[0].size();
// dist_path stores {distance, path_string} for each cell
vector<vector<pair<int, string>>> dist_path(m, vector<pair<int, string>>(n, {INT_MAX, ""}));
// Priority queue stores {distance, path_string, row, col}
// We need a custom comparator for min-heap behavior based on distance then path
auto comp = [](const auto& a, const auto& b) {
if (get<0>(a) != get<0>(b)) {
return get<0>(a) > get<0>(b);
}
return get<1>(a) > get<1>(b);
};
priority_queue<tuple<int, string, int, int>, vector<tuple<int, string, int, int>>, decltype(comp)> pq(comp);
dist_path[ball[0]][ball[1]] = {0, ""};
pq.emplace(0, "", ball[0], ball[1]);
// Directions: d, l, r, u (for lexicographical order of path)
vector<pair<int, int>> dirs = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
string dir_chars = "dlru";
while (!pq.empty()) {
auto [d, path, r, c] = pq.top();
pq.pop();
// If we found a better path already, skip
if (d > dist_path[r][c].first || (d == dist_path[r][c].first && path > dist_path[r][c].second)) {
continue;
}
// If we extract the hole, we are done because Dijkstra finds shortest path first.
if (r == hole[0] && c == hole[1]) {
return path;
}
for (int i = 0; i < 4; ++i) {
int dr = dirs[i].first;
int dc = dirs[i].second;
char dir_char = dir_chars[i];
int curr_r = r;
int curr_c = c;
int steps = 0;
// Roll the ball
while (true) {
int next_r = curr_r + dr;
int next_c = curr_c + dc;
if (next_r < 0 || next_r >= m || next_c < 0 || next_c >= n || maze[next_r][next_c] == 1) {
// Hit a wall or boundary, ball stops at (curr_r, curr_c)
if (steps > 0) {
int new_dist = d + steps;
string new_path = path + dir_char;
if (new_dist < dist_path[curr_r][curr_c].first ||
(new_dist == dist_path[curr_r][curr_c].first && new_path < dist_path[curr_r][curr_c].second)) {
dist_path[curr_r][curr_c] = {new_dist, new_path};
pq.emplace(new_dist, new_path, curr_r, curr_c);
}
}
break; // Stop rolling in this direction
}
curr_r = next_r;
curr_c = next_c;
steps++;
// Check for the hole
if (curr_r == hole[0] && curr_c == hole[1]) {
int new_dist = d + steps;
string new_path = path + dir_char;
if (new_dist < dist_path[hole[0]][hole[1]].first ||
(new_dist == dist_path[hole[0]][hole[1]].first && new_path < dist_path[hole[0]][hole[1]].second)) {
dist_path[hole[0]][hole[1]] = {new_dist, new_path};
pq.emplace(new_dist, new_path, hole[0], hole[1]);
}
break; // Stop rolling, ball fell in hole
}
}
}
}
if (dist_path[hole[0]][hole[1]].first == INT_MAX) {
return "impossible";
}
return dist_path[hole[0]][hole[1]].second;
}
};
The Maze III in TypeScript
type State = {
dist: number;
path: string;
r: number;
c: number;
};
// A basic Priority Queue implementation
class PriorityQueue<T> {
private heap: T[] = [];
private comparator: (a: T, b: T) => number;
constructor(comparator: (a: T, b: T) => number) {
this.comparator = comparator;
}
push(value: T): void {
this.heap.push(value);
this.siftUp();
}
pop(): T | undefined {
if (this.size() === 0) return undefined;
this.swap(0, this.size() - 1);
const poppedValue = this.heap.pop();
this.siftDown();
return poppedValue;
}
size(): number {
return this.heap.length;
}
private parent(i: number): number { return Math.floor((i - 1) / 2); }
private left(i: number): number { return 2 * i + 1; }
private right(i: number): number { return 2 * i + 2; }
private swap(i: number, j: number): void { [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; }
private siftUp(): void {
let node = this.size() - 1;
while (node > 0 && this.comparator(this.heap[node], this.heap[this.parent(node)]) < 0) {
this.swap(node, this.parent(node));
node = this.parent(node);
}
}
private siftDown(): void {
let node = 0;
while (
(this.left(node) < this.size() && this.comparator(this.heap[this.left(node)], this.heap[node]) < 0) ||
(this.right(node) < this.size() && this.comparator(this.heap[this.right(node)], this.heap[node]) < 0)
) {
let maxChild = (this.right(node) < this.size() && this.comparator(this.heap[this.right(node)], this.heap[this.left(node)]) < 0) ? this.right(node) : this.left(node);
this.swap(node, maxChild);
node = maxChild;
}
}
}
function findShortestWay(maze: number[][], ball: number[], hole: number[]): string {
const m = maze.length;
const n = maze[0].length;
const distPath: { dist: number; path: string; }[][] = Array(m).fill(0).map(() =>
Array(n).fill(0).map(() => ({ dist: Infinity, path: '' }))
);
const pq = new PriorityQueue<State>((a, b) => {
if (a.dist !== b.dist) return a.dist - b.dist;
return a.path.localeCompare(b.path);
});
distPath[ball[0]][ball[1]] = { dist: 0, path: '' };
pq.push({ dist: 0, path: '', r: ball[0], c: ball[1] });
const dirs = [[1, 0], [0, -1], [0, 1], [-1, 0]];
const dirChars = ['d', 'l', 'r', 'u'];
while (pq.size() > 0) {
const current = pq.pop()!;
const { dist, path, r, c } = current;
if (dist > distPath[r][c].dist || (dist === distPath[r][c].dist && path > distPath[r][c].path)) {
continue;
}
if (r === hole[0] && c === hole[1]) {
return path;
}
for (let i = 0; i < 4; i++) {
const [dr, dc] = dirs[i];
const dirChar = dirChars[i];
let currR = r, currC = c, steps = 0;
while (true) {
const nextR = currR + dr;
const nextC = currC + dc;
if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n || maze[nextR][nextC] === 1) {
if (steps > 0) {
const newDist = dist + steps;
const newPath = path + dirChar;
if (newDist < distPath[currR][currC].dist || (newDist === distPath[currR][currC].dist && newPath < distPath[currR][currC].path)) {
distPath[currR][currC] = { dist: newDist, path: newPath };
pq.push({ dist: newDist, path: newPath, r: currR, c: currC });
}
}
break;
}
currR = nextR;
currC = nextC;
steps++;
if (currR === hole[0] && currC === hole[1]) {
const newDist = dist + steps;
const newPath = path + dirChar;
if (newDist < distPath[hole[0]][hole[1]].dist || (newDist === distPath[hole[0]][hole[1]].dist && newPath < distPath[hole[0]][hole[1]].path)) {
distPath[hole[0]][hole[1]] = { dist: newDist, path: newPath };
pq.push({ dist: newDist, path: newPath, r: hole[0], c: hole[1] });
}
break;
}
}
}
}
return distPath[hole[0]][hole[1]].dist === Infinity ? 'impossible' : distPath[hole[0]][hole[1]].path;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.