头歌数据结构与算法课程设计中 - 迷宫问题

给定一个迷宫,给出起点和终点,找出从起点出发到终点的有效可行路径,并求出长度。迷宫可以用二维数组A来存储表示。0表示通路,1表示障碍。此处规定移动可以从上、下、左、右四个方向移动。坐标以行下标和列下标表示,均从0开始。迷宫可行路径可能有多条,且路径长度可能不一。输出路径长度最短路径。 输入描述: 第一行包含两个整数m与n,分别表示二维数组的行数、列数 第2~m+1行,每行包含n个数(0或1) 第m+2行包含两个整数表示起点的行下标和列下标 第m+3行包含两个整数表示终点的行下标和列下标 输出描述: 第一行输出从起点出发到终点的最短路径长度 第二行输出最短路径,路径以多个(x,y)坐标表示,每组坐标中间以空格分隔 输入样例: 5 5 0,0,0,0,0 0,1,0,1,0 0,1,1,0,0 0,1,1,0,1 0,0,0,0,0 0,0 4,4 输出样例: 8 (0, 0) (1, 0) (2, 0) (3, 0) (4, 0) (4, 1) (4, 2) (4, 3) (4, 4)

from collections import deque


def find_shortest_path(maze, start, end):
    rows, cols = len(maze), len(maze[0])

    # 初始化方向数组,表示上、下、左、右四个方向
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

    # 创建一个队列用于BFS
    queue = deque([(start, [start], 0)])  # (当前位置, 路径, 路径长度)
    visited = set([start])  # 已访问过的位置集合
    maze[start[0]][start[1]] = -1  # 标记起点为已访问

    while queue:
        current_pos, path, length = queue.popleft()

        if current_pos == end:
            return length, path

        for dx, dy in directions:
            new_x, new_y = current_pos[0] + dx, current_pos[1] + dy

            # 检查新位置是否合法
            if 0 <= new_x < rows and 0 <= new_y < cols and maze[new_x][new_y] == 0:
                new_pos = (new_x, new_y)
                if new_pos not in visited:
                    visited.add(new_pos)
                    maze[new_x][new_y] = -1  # 标记为已访问
                    queue.append((new_pos, path + [new_pos], length + 1))

    return None, None  # 如果没有找到路径,返回None


def print_maze(maze):
    for row in maze:
        print(','.join(map(str, row)))


m, n = map(int, input().split())
maze = [list(map(int, input().strip().split(','))) for _ in range(m)]
start_input = input().strip()
start_coords = start_input.split(',')
start_x, start_y = map(int, start_coords)
end_input = input().strip()
end_coords = end_input.split(',')
end_x, end_y = map(int, end_coords)
start = (start_x, start_y)
end = (end_x, end_y)

# 查找最短路径
length, path = find_shortest_path(maze, start, end)

# 输出结果
if length is not None:
    print(length)
    print(' '.join(f'({x}, {y})' for (x, y) in path))
else:
    print("No path found.")

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学不好python的小猫

感谢您的支持,我会长期更新我的

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值