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
Example 1:
Input:
map =
[
[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]
end = [3,2]
Output:
false
Example 2:
Input:
map =
[[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]
end = [4,4]
Output:
true
Notice
1.There is only one ball and one destination in the maze.
2.Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
3.The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
5.The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.
思路:球选择一个方向,然后一直走到头,这里tricky的地方就是,要用while循环判断下一个点是否合法来模拟一直走。while(isvalid(maz, nx + dx[k], ny + dy[k]) ,isvalid是判断是否走到墙的位置;T:O(M*N) , S:O(M*N)
class Solution {
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(start);
int[][] dirs = new int[][] {{0,1},{0,-1}, {-1,0},{1,0}};
int m = maze.length;
int n = maze[0].length;
boolean[][] visited = new boolean[m][n];
while(!queue.isEmpty()) {
int[] node = queue.poll();
int x = node[0];
int y = node[1];
if(x == destination[0] && y == destination[1]) {
return true;
}
if(visited[x][y]) {
continue;
}
visited[x][y] = true;
for(int[] dir: dirs) {
int nx = x;
int ny = y;
while(isvalid(nx + dir[0], ny + dir[1], maze)) {
nx += dir[0];
ny += dir[1];
}
queue.offer(new int[]{nx, ny});
}
}
return false;
}
private boolean isvalid(int x, int y, int[][] maze) {
int m = maze.length;
int n = maze[0].length;
return (0 <= x && x < m && 0 <= y && y < n && maze[x][y] != 1);
}
}