[LeetCode] The Maze

490. The Maze

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 true if the ball can stop at the destination, otherwise return false.

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
28
29
30
31
class Solution {

public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
if(start == destination) return true;

int n = maze.size(), m = maze[0].size();
int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0};
maze[start[0]][start[1]] = -1;
queue<vector<int>> q;
q.push(start);
while(!q.empty()) {
auto pos = q.front(); q.pop();
int y = pos[0], x = pos[1];
for(int i = 0; i < 4; i++) {
int ny = y, nx = x;

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 straight
ny += dy[i];
nx += dx[i];
}
if(!maze[ny][nx]) {
maze[ny][nx] = -1;
q.push({ny,nx});
if(destination[0] == ny and destination[1] == nx) return true;
}
}
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/19/PS/LeetCode/the-maze/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.