Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Union-Find - Maze Write a program that generates mazes of arbitrary size using t

ID: 3863468 • Letter: U

Question

Union-Find - Maze Write a program that generates mazes of arbitrary size using the union-find algorithm. A simple algorithm to generate the maze is to start by creating an N x M grid of cells separated by walls on all sides, except for entrance and exit. Then continually choose a wall randomly, and knock it down if the cells are not already connected to each other. If we repeat the process until the starting and ending cells are connected, we have a maze, it is better to continue knocking down the walls until every cell is reachable from every cell as this would generate more false leads in the maze. Test you algorithm by creating a 10 times 10 grid, and print all the walls that have been knocked down. Draw the resulting maze (hand-drawing is acceptable)

Explanation / Answer

Answer:

import random
import sys

X = 10
Y = 10

class Cell():

    def __init__(self, x, y):
        self.x, self.y = x, y
        self.right_wall = self.down_wall = None

class Wall():
    def __init__(self):
        self.neighbours = None
        self.active = True

def popall(seq):

    return seq.pop(random.randrange(len(seq)))

cells = {}
walls = []


for y in range(Y):
    for x in range(X):
        cells[(x, y)] = Cell(x, y)

for y in range(Y):
    for x in range(X):
        current_cell = cells[(x,y)]
        down_wall = Wall()
        current_cell.down_wall = down_wall
        right_wall = Wall()
        current_cell.right_wall = right_wall
        if y != Y-1:
            down_wall.neighbours = (current_cell, cells[(x,y+1)])
            walls.append(down_wall)

        if x != X-1:
            right_wall.neighbours = (current_cell, cells[(x+1,y)])
            walls.append(right_wall)


cell_list = [cells[key] for key in cells]

maze = (cell_list)

for _ in range(len(walls)):
    wall = popall(walls)
    cell_1, cell_2 = wall.neighbours
maze_map = []

x_max = (X*2)+1
y_max = (Y*2)+1


maze_map.append([True for _ in range(x_max)])
for y in range(1, y_max):
    maze_map.append([True]+[False for _ in range(1, x_max)])

for coords, cell in cells.items():
    x, y = coords
    maze_map[(y*2)+1][(x*2)+2] = True
    if cell.right_wall.active:
        maze_map[(y*2)+2][(x*2)+2] = True


def outprint(string):
    sys.stdout.write(string)


for row in maze_map:
    for tick in row:
        if tick: outprint('#'),
        else: outprint('_'),
    outprint(' ')