[LintCode] Problem 787 - The Maze

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.

Note

  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.
  4. The maze contains at least 2 empty spaces, and both the width and height of the maze won’t exceed 100.

Example

No.1

Input:

1
2
3
4
5
6
7
8
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

No.2

Input:

1
2
3
4
5
6
7
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

Code

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
34
35
36
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
int n = maze.length;
int m = maze[0].length;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int[][] visit = new int[n][m];
Queue<int[]> queue = new LinkedList<>();
visit[start[0]][start[1]] = 1;
queue.offer(start);

while (!queue.isEmpty()) {
int[] position = queue.poll();

if (destination[0] == position[0] && destination[1] == position[1])
return true;

for (int[] direction : directions) {
int x = position[0];
int y = position[1];

while (x >= 0 && y >= 0 && x < n && y < m && maze[x][y] == 0) {
x += direction[0];
y += direction[1];
}

x -= direction[0];
y -= direction[1];

if (visit[x][y] == 0) {
visit[x][y] = 1;
queue.offer(new int[] {x, y});
}
}
}

return false;
}