505 The Maze II
Last updated
Last updated
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.
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 start and destination coordinates are represented by row and column indexes.
Example 1
Example 2
Complexity: O(C^n) (exponential) time and space
The Idea: First identify whether or not the destination is reachable. In order for a destination to become reachable, if must (1) not be surrounded by sides, and (2) must contain at least 2 orthogonal walls. Next, we begin a BFS with a few modifications. As we carry along our BFS, we maintain memory our present location, the total distance traveled, and the previous direction. Within our BFS procedure, we check all the possible directions we can go: left, right, down, left. If the direction is viable, then we roll in said direction. A roll is defined to move from the parent location to a specified direction until a wall or edge is reached. In this method, a new node is returned to represent the new state in the maze. An additional optimization is made in order to check before any roll is made, that is, if the previous roll direction was in parallel to the new target direction, then the roll is not made. The purpose is to remove redundant moves (if the previous move is down, going back up will not get us anywhere). If at any time the parent node contains the destination coordinates, we return the distance traveled of said node.