Problem description:

There is a ball in a maze with empty spaces and walls. The ball can go through 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 ball’s start position, the destination and the maze, determine whether the ball could stop at the destination.

The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input 1: a maze represented by a 2D array

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

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)

Output: true

Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Example 2:

Input 1: a maze represented by a 2D array

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

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2)

Output: false

Explanation: There is no way for the ball to stop at the destination.

Solution:

  • DFS
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
32
33
class Solution {
public:
vector<vector<int>> direction{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
set<vector<int>> visited;
return dfs(maze, start, destination, visited);
}

bool dfs(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination, set<vector<int>>& visited){
if(start == destination) return true;
if(visited.find(start) != visited.end()) return false;
visited.insert(start);

for(int i= 0; i< direction.size(); i++){
auto res= Go2End(maze, start, direction[i]);
if(res == destination || dfs(maze, res, destination, visited))
return true;
}
return false;
}

vector<int> Go2End(vector<vector<int>>& maze, vector<int>& start, vector<int>& direction){
int i= start[0]+ direction[0];
int j= start[1]+ direction[1];
int m= maze.size();
int n= maze[0].size();

if(i < 0 || j < 0 || i >= m || j >= n || maze[i][j] == 1) return start;
vector<int> newStart{i, j};
return Go2End(maze, newStart, direction);

}
};

time complexity: $O()$
space complexity: $O()$
reference: