The part that got me was treating the stopping point correctly.
Model the problem as a graph where each cell is a node and edges represent rolling in one of the four directions until hitting a wall. Use BFS or DFS to explore all reachable stopping positions from the start, and check if the target is among them. Precompute the next stopping cell for each direction at each cell to avoid redundant simulation.
Pro tip: Clarify that the ball must stop exactly on the target, not just pass over it. Also, mention that you can optimize by precomputing the next stop for each cell and direction in O(mn) time, reducing the overall complexity to O(mn).
Confirm the grid dimensions, whether the start and target are guaranteed to be open, and if the ball can stop at the start if it's the target. Discuss boundary conditions and if the ball can get stuck.
Each state is a cell where the ball can stop. From a state, rolling in a direction leads to a new state (the cell before hitting a wall or boundary). This forms a directed graph.
Use BFS or DFS to explore all reachable states from the start. BFS is natural for finding if a target is reachable, but DFS works too. Track visited states to avoid cycles.
Precompute for each cell and direction the next stopping cell. This can be done by scanning rows and columns to find the nearest wall in each direction, reducing simulation time.
Time complexity is O(mn) with precomputation, otherwise O(mn * max(m,n)) if simulating each roll. Space is O(mn) for visited and precomputed arrays. Walk through a small example to verify.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.