Question

Union-Find - Maze Write a java program that generates mazes of arbitrary size using the union-find...

Union-Find - Maze Write a java 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 x 10 grid, and print all the walls that have been knocked down. Draw the resulting maze (hand-drawing is acceptable)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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('\n')

Add a comment
Know the answer?
Add Answer to:
Union-Find - Maze Write a java program that generates mazes of arbitrary size using the union-find...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT