787 · 迷宫 - LintCode
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.
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.
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
BFS
思路
简单的BFS。由于没有其他要求,我们只需要在BFS的过程中在队列里记录当前的坐标即可。
- 将地图的起点放入队列。
- 进行广度优先搜索。
- 每一次取出队首的元素,先判断是否到了终点,到了终点直接退出。
- 若没有到达,往四周的方向滚,直到滚到墙为止。若到达的位置没有被访问,那么加入队列中。
- 若整个过程都没有访问到终点,返回false即可。
题解
class Solution: """ @param maze: the maze @param start: the start @param destination: the destination @return: whether the ball could stop at the destination """ def hasPath(self, maze, start, destination): # write your code here dirs = [[-1, 0], [1, 0], [0,1], [0,-1]] queue = [] queue.append(start) visited = [[False]*len(maze[0]) for _ in range(len(maze))] visited[start[0]][start[1]] = True while queue: cur = queue.pop(0) if cur == destination: return True for dir in dirs: x, y = cur while 0 <= x < len(maze) and 0<= y < len(maze[0]) and maze[x][y] == 0: x += dir[0] y += dir[1] x -= dir[0] y -= dir[1] if visited[x][y] is False: queue.append([x, y]) visited[x][y] = True return False