给定一个迷宫,给出起点和终点,找出从起点出发到终点的有效可行路径,并求出长度。迷宫可以用二维数组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 dequedef find_shortest_path(maze, start, end):rows, cols = len(maze), len(maze[0])# 初始化方向数组,表示上、下、左、右四个方向directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]# 创建一个队列用于BFSqueue = 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, pathfor 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 # 如果没有找到路径,返回Nonedef 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.")