跳到主要内容

The Maze

描述

There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the 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 maze, the ball's start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return true if the ball can stop at the destination, otherwise return false.

You may assume that the borders of the maze are all walls (see examples).

Example 1:

Input: maze = [[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], destination = [4,4]
Output: true
Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.

Example 2:

Input: maze = [[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], destination = [3,2]
Output: false
Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.

Example 3:

Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
Output: false

Constraints:

  • 1 <= maze.length, maze[i].length <= 100
  • maze[i][j] is 0 or 1.
  • start.length == 2
  • destination.length == 2
  • 0 <= startrow, destinationrow <= maze.length
  • 0 <= startcol, destinationcol <= maze[i].length
  • Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
  • The maze contains at least 2 empty spaces.

分析

只需要输出 true或者false, 用 DFS 和 BFS 都可以。

代码

DFS

# The Maze
# DFS
# Time Complexity: O(mn), Space Complexity: O(mn)
class Solution:
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
m, n, visited = len(maze), len(maze[0]), set()
def dfs(x, y):
if (x, y) in visited:
return False
visited.add((x, y))
if [x, y] == destination:
return True
for i, j in (-1, 0), (1, 0), (0, -1), (0, 1):
newX, newY = x, y
# The ball won't stop rolling until hitting a wall
while 0 <= newX + i < m and 0 <= newY + j < n and maze[newX + i][newY + j] != 1:
newX += i
newY += j
if dfs(newX, newY):
return True
return False

return dfs(*start)

BFS

# The Maze
# BFS
# Time Complexity: O(mn), Space Complexity: O(mn)
class Solution:
def hasPath(self, maze, start, destination):
m = len(maze)
n = len(maze[0])
q = deque([start])

# Do NOT use visited = [[False] * n] * m
visited = [[False] * n for _ in range(m)]
visited[start[0]][start[1]] = True

while q:
x, y = q.popleft()
if [x, y] == destination: return True

for i, j in (-1, 0), (1, 0), (0, -1), (0, 1):
newX, newY = x, y
# The ball won't stop rolling until hitting a wall
while 0 <= newX + i < m and 0 <= newY + j < n and maze[newX + i][newY + j] == 0:
newX += i
newY += j
if not visited[newX][newY]:
q.append([newX, newY])
visited[newX][newY] = True

return False

相关题目