Comment on page

# 505 The Maze II

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
Input 1: a maze represented by a 2D array
0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0
Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)
Output: 12
Explanation: One shortest way is : left -> down -> left -> down -> right -> down -> right.
The total distance is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. Example 2
Input 1: a maze represented by a 2D array
0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0
Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2)
Output: -1
Explanation: There is no way for the ball to stop at the destination. 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.
Complexity: O(C^n) (exponential) time and space
import queue
import enum
import copy
class Node:
def __init__(self, r, c, dist, dir_):
self.r = r
self.c = c
self.dist = dist
self.dir_ = dir_
class Direction(enum.Enum):
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
NONE = 5
class Solution:
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
"""
def is_valid(r, c):
return 0 <= r < len(maze) and 0 <= c < len(maze) \
and maze[r][c] is not 1
def is_reachable(r, c):
# not to indicate "is blocked"
up = not is_valid(r - 1, c)
down = not is_valid(r + 1, c)
left = not is_valid(r, c - 1)
right = not is_valid(r, c + 1)
if up and down and left and right:
return False
elif (left and down) or (down and right) or (up and right) or (up and left):
return True
def roll(node, _dir):
node_cp = copy.deepcopy(node)
if _dir is Direction.UP:
node_cp.dir_ = Direction.UP
while is_valid(node_cp.r, node_cp.c):
node_cp.r -= 1
node_cp.dist += 1
node_cp.r += 1
elif _dir is Direction.DOWN:
node_cp.dir_ = Direction.DOWN
while is_valid(node_cp.r, node_cp.c):
node_cp.r += 1
node_cp.dist += 1
node_cp.r -= 1
elif _dir is Direction.LEFT:
node_cp.dir_ = Direction.LEFT
while is_valid(node_cp.r, node_cp.c):
node_cp.c -= 1
node_cp.dist += 1
node_cp.c += 1
elif _dir is Direction.RIGHT:
node_cp.dir_ = Direction.RIGHT
while is_valid(node_cp.r, node_cp.c):
node_cp.c += 1
node_cp.dist += 1
node_cp.c -= 1
node_cp.dist -= 1
return node_cp
if not is_reachable(destination, destination):
return -1
q = queue.Queue()
q.put(Node(start, start, 0, Direction.NONE))
while not q.empty():
front = q.get()
if front.r is destination \
and front.c is destination:
return front.dist
if is_valid(front.r - 1, front.c) \
and front.dir_ is not Direction.DOWN:
q.put(roll(front, Direction.UP))
if is_valid(front.r + 1, front.c) \
and front.dir_ is not Direction.UP:
q.put(roll(front, Direction.DOWN))
if is_valid(front.r, front.c - 1) \
and front.dir_ is not Direction.RIGHT:
q.put(roll(front, Direction.LEFT))
if is_valid(front.r, front.c + 1) \
and front.dir_ is not Direction.LEFT:
q.put(roll(front, Direction.RIGHT))
obj = Solution()
maze1 = [[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 0, 1, 1],
[0, 0, 0, 0, 0]]
print(obj.shortestDistance(maze1, [0, 4], [4, 4]))
print(obj.shortestDistance(maze1, [0, 4], [3, 2]))