LeetCode #490: The Maze

Oscar

May 22, 2020 11:23 Technology

This is a classic question solved by BFS method.

Description:

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, determine whether the ball could stop at the destination.

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:

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: true

Solution:

  • Traverse the maze with BFS method
def maze_bfs(array, start, target):
    nx = len(array[0]); ny = len(array)
    directions = [[1,0], [0,1], [-1, 0], [0, -1]]
    queue = [start]
    current = start
    while len(queue) > 0 and not (current[0] == target[0] and current[1] == target[1]):
        current = queue.pop(0)
        array[current[1]][current[0]] = 2
        print_maze(array)
        print('----------------')

        for d in directions:
            if (current[0]+d[0]<0) or (current[0]+d[0]>nx-1) or \
                    (current[1]+d[1]<0) or (current[1]+d[1]>ny-1) or \
                    array[current[1]+d[1]][current[0]+d[0]] > 0:
                continue
            else:
                queue.append([current[0]+d[0], current[1]+d[1]])
    return 

def print_maze(array):
    for row in array:
        out = []
        for x in row:
            if x == 0: out.append('0')
            if x == 1: out.append('#')
            if x == 2: out.append('*')
        print(''.join(out) )
    return

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]]
start = [4, 0]
target = [4, 4]

print(start, '->', target)
maze_bfs(array, start, target)
if array[target[1]][target[0]] == 2: print(True)
else: print(False)

 

Share this blog to:

1080 views,
0 likes, 0 comments

Login to comment