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.
Given the m x nmaze, the ball’s start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return the shortest distance for the ball to stop at the destination. If the ball cannot stop at destination, return -1.
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).
Input: maze =[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start =[0,4], destination =[4,4]Output: 12Explanation: One possible way is: left -> down -> left -> down -> right -> down -> right.The length of the path is1+1+3+1+2+2+2=12. Note that ehy have counted the number of stops(including direction changes) instead of counting every cell travelled.
Input: maze =[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start =[0,4], destination =[3,2]Output: -1Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
The key idea is to use Dijkstra’s algorithm to always expand the path with the minimum distance so far. For each position, roll the ball in all four directions until it hits a wall, and if the new distance is less than the previously recorded distance, update and push to the heap.
classSolution {
public:int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& dest) {
int m = maze.size(), n = maze[0].size();
vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
dist[start[0]][start[1]] =0;
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
pq.emplace(0, start[0], start[1]);
int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
while (!pq.empty()) {
auto [d, i, j] = pq.top(); pq.pop();
if (i == dest[0] && j == dest[1]) return d;
for (auto& dir : dirs) {
int x = i, y = j, cnt =0;
while (x+dir[0] >=0&& x+dir[0] < m && y+dir[1] >=0&& y+dir[1] < n && maze[x+dir[0]][y+dir[1]] ==0) {
x += dir[0]; y += dir[1]; cnt++;
}
if (dist[x][y] > d + cnt) {
dist[x][y] = d + cnt;
pq.emplace(dist[x][y], x, y);
}
}
}
return-1;
}
};
classSolution {
funshortestDistance(maze: Array<IntArray>, start: IntArray, dest: IntArray): Int {
val m = maze.size
val n = maze[0].size
val dist = Array(m) { IntArray(n) { Int.MAX_VALUE } }
dist[start[0]][start[1]] = 0val pq = java.util.PriorityQueue(compareBy<IntArray> { it[0] })
pq.add(intArrayOf(0, start[0], start[1]))
val dirs = arrayOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)
while (pq.isNotEmpty()) {
val(d, i, j) = pq.remove()
if (i == dest[0] && j == dest[1]) return d
for ((dx, dy) in dirs) {
var x = i; var y = j; var cnt = 0while (x+dx in0 until m && y+dy in0 until n && maze[x+dx][y+dy] ==0) {
x += dx; y += dy; cnt++ }
if (dist[x][y] > d + cnt) {
dist[x][y] = d + cnt
pq.add(intArrayOf(dist[x][y], x, y))
}
}
}
return -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defshortestDistance(self, maze: list[list[int]], start: list[int], dest: list[int]) -> int:
import heapq
m, n = len(maze), len(maze[0])
dist = [[float('inf')] * n for _ in range(m)]
dist[start[0]][start[1]] =0 h = [(0, start[0], start[1])]
while h:
d, i, j = heapq.heappop(h)
if [i, j] == dest:
return d
for dx, dy in ((0,1),(1,0),(0,-1),(-1,0)):
x, y, cnt = i, j, 0while0<= x+dx < m and0<= y+dy < n and maze[x+dx][y+dy] ==0:
x += dx; y += dy; cnt +=1if dist[x][y] > d + cnt:
dist[x][y] = d + cnt
heapq.heappush(h, (dist[x][y], x, y))
return-1
Dijkstra is the most natural choice because edge weights (the number of cells rolled between stopping points) vary. However, you can convert the problem into a unit-weight graph by expanding the state to include the current moving direction. If you simulate the ball’s motion one empty cell at a time and treat each step as weight 1, a plain BFS finds the shortest number of cell-steps needed to reach a stopping state at the destination. The trick is to only allow direction changes when the ball is stopped (i.e., the next cell in the current direction is a wall).
This produces a state-space of size O(m * n * 4) (4 directions per cell). Each transition either moves the ball one cell forward in the same direction (cost 1) or — when blocked — switches direction at the same cell (cost 0). Representing turning as a zero-cost transition still works with BFS because we enqueue turn states without increasing distance (we don’t need 0-1 BFS here because turns can be processed immediately without enqueuing extra distance). In practice the algorithm uses a deque/queue and marks visited (x,y,dir) to avoid revisits.
Model states as (x, y, dir) where dir is one of the four directions the ball will next attempt to roll.
Initialize the queue with the start cell and all 4 directions (distance 0). If the start is already the destination and it’s a stopping cell (at least one direction immediately blocked), return 0.
While the queue is not empty, pop a state. If the next cell in the current direction is empty, step forward to (x+dx, y+dy, dir) with distance+1. If the next cell is a wall, the ball is stopped at (x, y): if (x, y) == destination, return the current distance; otherwise enqueue the same cell with all other directions (turns) at the same distance (if not visited).
If the BFS completes without finding a stopping state at destination, return -1.
This BFS simulates the ball moving one cell at a time, so distances are exactly the number of empty spaces traversed and the first time we reach a stopping state at destination is the shortest distance.
classSolution {
public:int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& dest) {
int m = maze.size(), n = maze[0].size();
if (start == dest) {
// If start==dest and it's already a stopping cell, distance is 0.
for (auto&d : vector<pair<int,int>>{{0,1},{1,0},{0,-1},{-1,0}}) {
int nx = start[0] + d.first, ny = start[1] + d.second;
if (nx <0|| nx >= m || ny <0|| ny >= n || maze[nx][ny] ==1) return0;
}
}
int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
// visited[x][y][dir]
vector<vector<array<bool,4>>> vis(m, vector<array<bool,4>>(n));
deque<tuple<int,int,int,int>> q; // x,y,dir,dist
for (int di =0; di <4; ++di) {
vis[start[0]][start[1]][di] = true;
q.emplace_back(start[0], start[1], di, 0);
}
while (!q.empty()) {
auto [x,y,di,dist] = q.front(); q.pop_front();
int dx = dirs[di][0], dy = dirs[di][1];
int nx = x + dx, ny = y + dy;
if (nx >=0&& nx < m && ny >=0&& ny < n && maze[nx][ny] ==0) {
// Move one step forward in the same direction
if (!vis[nx][ny][di]) {
vis[nx][ny][di] = true;
q.emplace_back(nx, ny, di, dist +1);
}
} else {
// We are stopped at (x,y)
if (x == dest[0] && y == dest[1]) return dist;
// Try turning to other directions (cost 0)
for (int ndi =0; ndi <4; ++ndi) {
if (ndi == di) continue;
if (!vis[x][y][ndi]) {
vis[x][y][ndi] = true;
q.emplace_back(x, y, ndi, dist);
}
}
}
}
return-1;
}
};
from collections import deque
classSolution:
defshortestDistance(self, maze: list[list[int]], start: list[int], dest: list[int]) -> int:
m, n = len(maze), len(maze[0])
sx, sy = start
dxs = [(0,1),(1,0),(0,-1),(-1,0)]
# Quick check: start == dest and stoppableif start == dest:
for dx, dy in dxs:
nx, ny = sx + dx, sy + dy
if nx <0or nx >= m or ny <0or ny >= n or maze[nx][ny] ==1:
return0# visited[x][y][dir] visited = [[[False]*4for _ in range(n)] for __ in range(m)]
q = deque()
for di in range(4):
visited[sx][sy][di] =True q.append((sx, sy, di, 0))
while q:
x, y, di, dist = q.popleft()
dx, dy = dxs[di]
nx, ny = x + dx, y + dy
if0<= nx < m and0<= ny < n and maze[nx][ny] ==0:
ifnot visited[nx][ny][di]:
visited[nx][ny][di] =True q.append((nx, ny, di, dist +1))
else:
# stopped at (x, y)if [x, y] == dest:
return dist
for ndi in range(4):
if ndi == di: continueifnot visited[x][y][ndi]:
visited[x][y][ndi] =True q.append((x, y, ndi, dist))
return-1
⏰ Time complexity: O(m * n) – there are O(m * n * 4) states (4 directions per cell) and each state is processed at most once; each transition is O(1), so overall O(m * n).
🧺 Space complexity: O(m * n) – visited/state bookkeeping requires O(m * n * 4) bits/booleans which is O(m * n).