[LeetCode] The Maze II

505. The Maze II

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 n maze, 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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
if(start == destination) return 0;
int dy[4] = {-1,0,1,0}, dx[4] = {0,1,0,-1}, n = maze.size(), m = maze[0].size();
priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq;
pq.push({0,start[0],start[1]});
int v[n][m];
memset(v,-1,sizeof(v));
while(!pq.empty()) {
auto [mv, y, x] = pq.top(); pq.pop();
for(int i = 0; i < 4; i++) {
int ny = y, nx = x, move = 0;
while(0 <= ny + dy[i] and ny + dy[i] < n and 0 <= nx + dx[i] and nx + dx[i] < m and maze[ny + dy[i]][nx + dx[i]] == 0) {
move++;
ny += dy[i], nx += dx[i];
}
if(v[ny][nx] == -1 or v[ny][nx] > move + mv) {
v[ny][nx] = move + mv;
pq.push({move + mv, ny, nx});
if(ny == destination[0] and nx == destination[1]) return move + mv;
}
}
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/26/PS/LeetCode/the-maze-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.