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 m x nmaze, 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.
Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
The maze contains at least 2 empty spaces.
Solutions
Solution 1: DFS
Thinking
The ball rolls until it hits a wall; we ask whether it can stop on the destination. Walking cell by cell confuses βpassing throughβ with βstoppingβ.
DFS: from a stop, roll in each direction to a wall or border and recurse on that stop. A visited grid marks stops only. The destination is reachable once it is marked.
The inner \(\textit{while}\) rolls without marking cells on the way; the state space is stops, not every empty cell.
Roll in four directions until hitting a wall, and DFS every stoppable cell from the start.
Solution 1 is recursive. The same rolling rule works with a queue: enqueue stops, and return as soon as the destination is reached. No call-stack depth, which is enough for a yes/no reachability query.
Roll in four directions and BFS the stoppable cells until the destination is reached.