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
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:
- There is only one ball and one destination in the maze.
- Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
- 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.
- The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.
有一个球在一个二维数组表示的空间里,1代表是墙,0代表是空,边界可以看作是墙。球可以向上下左右四个方向滚动,每一次滚动到墙才停止然后进行下一次滚动。求球是否可以滚动到终点。
解法1:DFS,可能TLE。首先判断是否已经到达了终点,如果是则直接返回true;否则就看该位置是否已经被访问过了,如果是则返回,否则就记当前位置已经被访问。然后用DFS尝试四个不同方向,有任何一个方向可以到达终点就直接返回true。
解法2: BFS。建立一个queue,先将start位置放入队列。每次从队列头部拿出一个位置,如果此位置是终点则直接返回true,否则就看该位置是否被访问过,如果没有被访问,将其四个方向上移动可以停靠的点加入队列,此位置记为已访问。如果队列空了还没有发现可以到达的路径,说明无法到达了。
Java:
public class Solution {
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
if(maze.length == 0 || maze[0].length == 0) return false;
if(start[0] == destination[0] && start[1] == destination[1]) return true;
m = maze.length; n = maze[0].length;
boolean[][] visited = new boolean[m][n];
return dfs(maze, start, destination, visited);
}
int m, n;
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private boolean dfs(int[][] maze, int[] cur, int[] dest, boolean[][] visited) {
// already visited
if(visited[cur[0]][cur[1]]) return false;
// reach destination
if(Arrays.equals(cur, dest)) return true;
visited[cur[0]][cur[1]] = true;
for(int[] dir : dirs) {
int nx = cur[0], ny = cur[1];
while(notWall(nx + dir[0], ny + dir[1]) && maze[nx+dir[0]][ny+dir[1]] != 1) {
nx += dir[0]; ny += dir[1];
}
if(dfs(maze, new int[] {nx, ny}, dest, visited)) return true;
}
return false;
}
private boolean notWall(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
}
Python:
class Solution(object):
def hasPath(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: bool
"""
start = tuple(start)
destination = tuple(destination)
if start == destination:
return True
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
width = len(maze)
height = len(maze[0])
if 1 <= destination[0] < width-1 and 1 <= destination[1] < height-1:
if not any([maze[destination[0]+direction[0]][destination[1]+direction[1]] for direction in directions]):
return False
positions = [start]
visited = set()
while positions:
position = positions.pop(0)
for direction in directions:
if (position + direction) in visited: continue
nextPosition = position
while (nextPosition+direction) not in visited:
visited.add(nextPosition+direction)
prevPosition = nextPosition
nextPosition = (nextPosition[0]+direction[0], nextPosition[1]+direction[1])
if not 0 <= nextPosition[0] < width or not 0 <= nextPosition[1] < height or maze[nextPosition[0]][nextPosition[1]] == 1:
if prevPosition == destination:
return True
positions.append(prevPosition)
break
return False
C++: DFS
class Solution {
public:
vector> dirs{{0,-1},{-1,0},{0,1},{1,0}};
bool hasPath(vector>& maze, vector& start, vector& destination) {
if (maze.empty() || maze[0].empty()) return true;
int m = maze.size(), n = maze[0].size();
vector> dp(m, vector(n, -1));
return helper(maze, dp, start[0], start[1], destination[0], destination[1]);
}
bool helper(vector>& maze, vector>& dp, int i, int j, int di, int dj) {
if (i == di && j == dj) return true;
if (dp[i][j] != -1) return dp[i][j];
bool res = false;
int m = maze.size(), n = maze[0].size();
maze[i][j] = -1;
for (auto dir : dirs) {
int x = i, y = j;
while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] != 1) {
x += dir[0]; y += dir[1];
}
x -= dir[0]; y -= dir[1];
if (maze[x][y] != -1) {
res |= helper(maze, dp, x, y, di, dj);
}
}
dp[i][j] = res;
return res;
}
};
C++: BFS
class Solution {
public:
bool hasPath(vector>& maze, vector& start, vector& destination) {
if (maze.empty() || maze[0].empty()) return true;
int m = maze.size(), n = maze[0].size();
vector> visited(m, vector(n, false));
vector> dirs{{0,-1},{-1,0},{0,1},{1,0}};
queue> q;
q.push({start[0], start[1]});
visited[start[0]][start[1]] = true;
while (!q.empty()) {
auto t = q.front(); q.pop();
if (t.first == destination[0] && t.second == destination[1]) return true;
for (auto dir : dirs) {
int x = t.first, y = t.second;
while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0) {
x += dir[0]; y += dir[1];
}
x -= dir[0]; y -= dir[1];
if (!visited[x][y]) {
visited[x][y] = true;
q.push({x, y});
}
}
}
return false;
}
};
类似题目:
[LeetCode] 505. The Maze II 迷宫 II
[LeetCode] 499. The Maze III 迷宫 III
All LeetCode Questions List 题目汇总