编辑代码

# coding:utf-8
#JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
#print("Hello world!   -  python.jsrun.net .")
import random

def generate_maze(width, height):
    # 确保宽高至少为3,并且是奇数(保证路径生成正确)
    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()