There is aballin a maze with empty spaces and walls. The ball can go through empty spaces by rollingup,down,leftorright, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball'sstart position, thedestinationand themaze, 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
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.
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.
Note:
tag: BFS
class Solution {
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
if (maze == null || maze.length == 0) return false;
Set<Integer> seen = new HashSet<>();
Queue<int[]> q = new LinkedList<>();
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int n = maze.length, m = maze[0].length;
seen.add(start[0] * m + start[1]);
q.offer(start);
while (!q.isEmpty()){
int[] cur = q.poll();
if (cur[0] == destination[0] && cur[1] == destination[1]) return true;
for (int i = 0; i < 4; i++){
int xx = cur[0] + dirs[i][0];
int yy = cur[1] + dirs[i][1];
if (xx < 0 || xx >= n || yy < 0 || yy >= m || maze[xx][yy] == 1) continue;
while ( maze[xx][yy] != 1 ){
xx += dirs[i][0];
yy += dirs[i][1];
if (xx < 0 || xx >= n || yy < 0 || yy >= m) break;
}
xx -= dirs[i][0];
yy -= dirs[i][1];
int[] temp = {xx, yy};
if (!seen.contains(xx * m + yy)){
seen.add(xx * m + yy);
q.offer(temp);
//System.out.println("adding: " + " x: " + temp[0] + " y: " + temp[1]);
}
}
}
return false;
}
}