import random
def generate_maze(width, height):
if width % 2 == 0:
width += 1
if height % 2 == 0:
height += 1
maze = [['#' for _ in range(width)] for _ in range(height)]
start_x = 1
start_y = 1
maze[0][1] = 'E'
maze[height-1][width-2] = 'X'
def carve(x, y):
maze[y][x] = ' '
directions = [(0, -2), (2, 0), (0, 2), (-2, 0)]
random.shuffle(directions)
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 < nx < width-1 and 0 < ny < height-1:
if maze[ny][nx] == '#':
maze[y + dy//2][x + dx//2] = ' '
carve(nx, ny)
carve(start_x, start_y)
if not has_path(maze, 'E', 'X'):
maze = generate_maze(width, height)
return maze
def has_path(maze, start_char, end_char):
"""检查是否存在从start_char到end_char的路径"""
start = None
for y, row in enumerate(maze):
for x, cell in enumerate(row):
if cell == start_char:
start = (x, y)
break
if start:
break
if not start:
return False
visited = set()
stack = [start]
while stack:
x, y = stack.pop()
if maze[y][x] == end_char:
return True
if (x, y) not in visited:
visited.add((x, y))
directions = [(0, -1), (1, 0), (0, 1), (-1, 0)]
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < len(maze[0]) and 0 <= ny < len(maze):
if maze[ny][nx] in [' ', end_char]:
stack.append((nx, ny))
return False
def print_maze(maze):
"""打印迷宫"""
for row in maze:
print(''.join(row))
def main():
try:
width = int(input("请输入迷宫宽度(至少3): "))
height = int(input("请输入迷宫高度(至少3): "))
except ValueError:
print("请输入有效的数字!")
return
if width < 3 or height < 3:
print("迷宫尺寸太小!")
return
maze = generate_maze(width, height)
print("\n生成的迷宫:")
print_maze(maze)
if __name__ == "__main__":
main()