Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 – Depth-First Search (DFS) (1)
Intuition
The key idea is to use DFS to simulate the ball rolling in all four directions from the start position. The ball keeps rolling until it hits a wall, and we recursively check if the destination can be reached from the stopping point. We use a visited matrix to avoid cycles.
Approach
- Initialize a visited matrix to track visited positions.
- Start DFS from the start position.
- For each direction, roll the ball until it hits a wall.
- If the stopping position has not been visited, recursively call DFS from there.
- If the destination is reached, return true.
- If all paths are explored and the destination is not reached, return false.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(mn)
, where m and n are the maze dimensions; each cell is visited at most once. - 🧺 Space complexity:
O(mn)
, for the visited matrix and recursion stack.