Problem Description
Given a maze where empty spaces are 0 and walls are 1, a ball rolls one direction until hitting a wall. There is a single hole in the maze. Starting from the ball’s position, determine the instruction string (using 'u', 'd', 'l', 'r') by which the ball can drop into the hole following the shortest distance. If more than one shortest path exists, return the lexicographically smallest string. If the ball cannot drop into the hole at all, return "impossible".
Key Insights
- The ball rolls continuously until hitting a wall or falling into the hole.
- A shortest path search is needed based on rolling distance (each step counts when passing an empty cell).
- Dijkstra’s algorithm (or a modified BFS with a priority queue) is appropriate since we need to consider distance and lexicographic order.
- When expanding moves, simulate the roll until the ball stops — if a hole is passed en route, use that stopping point.
- Track the best (distance, path) for each cell to avoid redundant work.
Space and Time Complexity
Time Complexity: O(mn log(mn)) where m and n are the maze dimensions
Space Complexity: O(mn)
Solution
We use a Dijkstra-like approach with a priority queue containing tuples of (distance, path, row, col). The priority queue is ordered by distance first and then by the instruction string lexicographically. For each cell, simulate rolling in each possible direction (up, down, left, right; iterated in alphabetical order so that the lexicographical property is maintained) until the ball stops. If the ball encounters the hole during rolling, treat that as a valid stop immediately. For every new stopping cell, if a shorter distance or lexicographically smaller path is found, update the record and add the new state to the priority queue. If you reach the hole, return the corresponding path string. If no solution is found when the queue is empty, return "impossible".