Rolling Ball Maze Reachability
Goldman SachsSoftware Engineer · OnsiteLast updated
This problem tests your ability to model a grid-based movement simulation as a graph reachability problem, requiring efficient state traversal.
Rolling Ball Maze
Given a 2D grid representing a maze, where 0 is an empty space and 1 is a wall, a ball starts at coordinate (start_row, start_col) and needs to reach (target_row, target_col).
The ball rolls in one of the four cardinal directions (Up, Down, Left, Right). Once the ball starts rolling in a direction, it continues moving in that straight line until it hits a wall or the boundary of the grid. Only after hitting a wall/boundary can the ball change its direction or stop at the cell immediately before the obstacle.
Implement a function to determine the minimum number of stops required to reach the target. If the target is unreachable, return -1.
Function Signature
def min_stops(maze, start, target) -> int
Constraints
mazeis an M x N grid (1 <= M, N <= 100).startandtargetare valid coordinates(r, c).- The ball must come to a complete stop before changing direction.
Examples
Example 1:
Input: maze = [[0, 0, 1], [0, 0, 0], [0, 1, 0]], start = (0, 0), target = (2, 2)
Output: 2
Explanation: Move Right to (0, 1) -> hit wall, then move Down to (2, 2).
Example 2:
Input: maze = [[0, 1], [1, 0]], start = (0, 0), target = (1, 1)
Output: -1
Explanation: The ball cannot navigate the corners to reach the target.
Hints
Hint 1
Model the grid as a graph where each 'stop' position is a node.
Hint 2
Use Breadth-First Search (BFS) to find the shortest path, as the problem asks for the minimum number of stops.
Hint 3
For each current cell, simulate rolling in all four directions until hitting a wall to determine the valid next 'stop' nodes.
Follow-up questions
- How would your approach change if you wanted the minimum total distance traveled instead of the minimum number of stops?
- What is the time complexity of your solution in terms of grid dimensions M and N?
- How would you handle a scenario where the maze contains 'teleporters' that move the ball to a different cell instantly?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.