使用Dijkstra算法遍历迷宫时遇AttributeError错误求助
迷宫Dijkstra算法实现错误排查与修复
问题概述
尝试用Dijkstra算法实现迷宫导航时遇到错误,最初被提示在if语句末尾加.any(),修改为if Maze[tuple(currentCoords)] == "_".any():后触发:
AttributeError: 'str' object has no attribute 'any'
代码目标是遍历迷宫并检查可用格子,当前代码逻辑存在多处问题,以下是原代码及修复建议。
错误原因分析
.any()是NumPy数组的方法,不能直接用在字符串"_"上,原逻辑想判断当前坐标是否为空白格"_",但写法完全错误。CurrentValue初始值是字符串"Y",直接int(CurrentValue)会报错,因为无法将字母转整数。- 坐标处理错误:
Y = currentCoords[-7]完全不符合二维坐标的取值逻辑,currentCoords[-1]是当前点的[x,y]数组,应该分别提取x和y。 - 仅检查左和上两个方向,遗漏右和下,导致路径搜索不完整。
- 缺失Dijkstra核心逻辑:没有维护距离表或优先队列,当前写法更类似广度优先搜索的错误实现。
修复后的代码
import time import numpy as np # 7x7迷宫:X是起点,_是空路,Y是终点,Z是障碍物 Maze = np.array([ "X", "_", "_", "_", "_", "Z", "_", "_", "Z", "Z", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "_", "_", "_", "_", "_", "_", "Z", "_", "Z", "Z", "_", "_", "_", "Z", "_", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "Y" ]).reshape((7, 7)) # 初始化距离矩阵,-1表示未访问,起点距离为0 distance = np.full((7,7), -1) start_pos = tuple(np.argwhere(Maze == "X")[0]) end_pos = tuple(np.argwhere(Maze == "Y")[0]) distance[start_pos] = 0 # 四个移动方向:上下左右 directions = [(-1,0), (1,0), (0,-1), (0,1)] # 广度优先搜索(因每步权重相同,等价于Dijkstra算法) queue = [start_pos] found = False while queue and not found: current_x, current_y = queue.pop(0) current_dist = distance[current_x, current_y] for dx, dy in directions: new_x = current_x + dx new_y = current_y + dy # 检查坐标合法性、是否为障碍物、是否未被访问 if 0 <= new_x <7 and 0 <= new_y <7: if Maze[new_x, new_y] == "Y": print("找到终点!最短路径长度:", current_dist + 1) found = True break elif Maze[new_x, new_y] == "_" and distance[new_x, new_y] == -1: distance[new_x, new_y] = current_dist + 1 Maze[new_x, new_y] = str(current_dist + 1) queue.append((new_x, new_y)) # 打印当前迷宫状态(可选,用于观察搜索过程) print(Maze) time.sleep(0.5) # 回溯路径(从终点倒推回起点) if found: path = [end_pos] current_x, current_y = end_pos while (current_x, current_y) != start_pos: for dx, dy in directions: prev_x = current_x + dx prev_y = current_y + dy if 0 <= prev_x <7 and 0 <= prev_y <7: if distance[prev_x, prev_y] == distance[current_x, current_y] -1: path.append((prev_x, prev_y)) current_x, current_y = prev_x, prev_y break path.reverse() print("最短路径坐标:", path)
关键修改点说明
- 改用广度优先搜索(迷宫每步权重相同,BFS等价于Dijkstra),更易实现且符合需求。
- 新增
distance矩阵记录每个格子到起点的距离,避免重复访问。 - 修复坐标处理逻辑,正确提取x/y值,遍历四个移动方向。
- 移除错误的
.any()用法,直接判断格子值是否为目标字符。 - 添加路径回溯功能,找到终点后倒推输出完整路径。
- 修复类型错误:不再尝试将字母
Y转整数,从起点开始累加距离。
内容的提问来源于stack exchange,提问作者EMarb187
相关产品推荐
相关产品推荐

