499 The Maze III
499. The Maze III
1. Question
There is aballin a maze with empty spaces and walls. The ball can go through empty spaces by rollingup(u),down(d),left(l) orright(r), but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also aholein this maze. The ball will drop into the hole if it rolls on to the hole.
Given the ball position, the hole positionand the maze, find out how the ball could drop into the hole by moving theshortest distance. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the hole (included). Output the moving directionsby using 'u', 'd', 'l' and 'r'. Since there could be several different shortest ways, you should output the lexicographically smallest way. If the ball cannot reach the hole, output "impossible".
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The ball and the hole coordinates are represented by row and column indexes.
Example 1
Example 2
Note:
There is only one ball and one hole in the maze.
Both the ball and hole exist on an empty space, and they will not be at the same position initially.
The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
The maze contains at least 2 empty spaces, and the width and the height of the maze won't exceed 30.
2. Implementation
(1) BFS:
3. Time & Space Complexity
BFS: 时间复杂度O(m * n * Max(m,n)),空间复杂度O(mn)
Last updated