|
| 1 | +""" |
| 2 | +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. |
| 3 | +
|
| 4 | +Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination. |
| 5 | +
|
| 6 | +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. |
| 7 | +
|
| 8 | + |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input 1: a maze represented by a 2D array |
| 13 | +
|
| 14 | +0 0 1 0 0 |
| 15 | +0 0 0 0 0 |
| 16 | +0 0 0 1 0 |
| 17 | +1 1 0 1 1 |
| 18 | +0 0 0 0 0 |
| 19 | +
|
| 20 | +Input 2: start coordinate (rowStart, colStart) = (0, 4) |
| 21 | +Input 3: destination coordinate (rowDest, colDest) = (4, 4) |
| 22 | +
|
| 23 | +Output: true |
| 24 | +
|
| 25 | +Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right. |
| 26 | +
|
| 27 | +Example 2: |
| 28 | +
|
| 29 | +Input 1: a maze represented by a 2D array |
| 30 | +
|
| 31 | +0 0 1 0 0 |
| 32 | +0 0 0 0 0 |
| 33 | +0 0 0 1 0 |
| 34 | +1 1 0 1 1 |
| 35 | +0 0 0 0 0 |
| 36 | +
|
| 37 | +Input 2: start coordinate (rowStart, colStart) = (0, 4) |
| 38 | +Input 3: destination coordinate (rowDest, colDest) = (3, 2) |
| 39 | +
|
| 40 | +Output: false |
| 41 | +
|
| 42 | +Explanation: There is no way for the ball to stop at the destination. |
| 43 | +
|
| 44 | + |
| 45 | +
|
| 46 | +Note: |
| 47 | +
|
| 48 | +There is only one ball and one destination in the maze. |
| 49 | +Both the ball and the destination exist on an empty space, and they will not be at the same position initially. |
| 50 | +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. |
| 51 | +The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100. |
| 52 | +""" |
| 53 | +class Solution: |
| 54 | + def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: |
| 55 | + seen = set() |
| 56 | + def dfs(i,j): |
| 57 | + if [i,j] == destination: |
| 58 | + return True |
| 59 | + for dx,dy in ((0,-1),(0,1),(1,0),(-1,0)): |
| 60 | + x,y = i,j |
| 61 | + while 0 <= x+dx < len(maze) and 0 <= y+dy < len(maze[0]) and not maze[x+dx][y+dy]: |
| 62 | + x = x + dx |
| 63 | + y = y + dy |
| 64 | + if not (x,y) in seen: |
| 65 | + seen.add((x,y)) |
| 66 | + if dfs(x,y): |
| 67 | + return True |
| 68 | + return False |
| 69 | + return dfs(start[0],start[1]) |
0 commit comments