Problem Description
There is a ball in a maze represented by a 2D grid where empty spaces are marked as 0 and walls as 1. The ball can roll continuously in one of the four cardinal directions (up, down, left, right) until it meets a wall, and then it can choose a new direction. Given the maze, a starting position, and a destination position, determine if the ball can stop exactly at the destination.
Key Insights
- The ball continues moving in one direction until it hits a wall (or the boundary, which is considered a wall).
- You must simulate the ball's rolling rather than taking a single step.
- Even if the ball passes through the destination, it is only valid if it can stop exactly there.
- A breadth-first search (BFS) or depth-first search (DFS) strategy is ideal because we need to explore all stopping positions.
- Use a visited structure to avoid revisiting positions and thus prevent infinite loops.
Space and Time Complexity
Time Complexity: O(m * n) where m and n are the dimensions of the maze. Space Complexity: O(m * n) due to the storage used by the visited matrix and the BFS/DFS queue or recursion stack.
Solution
We simulate the ball's movement using a breadth-first search (BFS) approach. Each time we pick a stop position, we try to roll in all four directions until the ball hits a wall. At that point, if the new stopping position has not been visited, we mark it as visited and add it to our queue. If we ever reach the destination exactly, we return true. The key is simulating the "roll" by iteratively moving in a direction until no further move is possible.
We store the coordinates in a queue (or stack for DFS) along with a 2D visited array to monitor which positions have been processed. The directions are maintained in a list/array, and for each direction, we keep moving until the next cell would be out of bounds or a wall.