编写Dijkstra算法遇数组越界错误,求修复方案
修复Dijkstra迷宫算法中的数组越界错误
尝试用Dijkstra算法求解7x7迷宫路径时遇到数组越界错误,报错信息如下:
Traceback (most recent call last): File "c:\Users\User\Retake\code\Dijkstra\maze.py", line 27, in <module> neighbors.append((currentCoords[0, 0] - 1, currentCoords[0, 1])) IndexError: index 1 is out of bounds for axis 1 with size 1
当前代码实现如下:
import numpy as np # The 7 by 7 grid provided. X is the starting square, # _ represents a square, Y is the finishing square # and Z is an obstacle. Maze = np.array([ "X", "_", "_", "_", "_", "Z", "_", "_", "Z", "Z", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "_", "_", "_", "_", "_", "_", "Z", "_", "Z", "Z", "_", "_", "_", "Z", "_", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "Y" ]) CurrentValue = "Y" # If not on the starting square, the robot will move to # a new square and check if it is an obstacle or a new # square. while CurrentValue != "X": currentCoords = np.argwhere(Maze == CurrentValue) #print("Current Coordinates:", currentCoords[-1]) RightCoords = {6, 13, 20, 27, 34, 41, 48} if currentCoords == RightCoords: pass # If the new square is an empty space, mark it as the current value + 1. print(Maze[tuple(currentCoords[-1])]) if Maze[tuple(currentCoords[-1])] == "_": Maze[tuple(currentCoords[-1])] = str(int(CurrentValue) + 1) elif Maze[tuple(currentCoords[-1])] == "X": print("Maze:", Maze) CurrentValue = "X" #print("Current Value:", CurrentValue) # Move to the left and update the current value accordingly. #currentCoords[-1][1] = 1 # The while loop ends when the robot reaches the starting square "Y". #print("Maze:", Maze)
问题根源分析
- 数组维度错误:你把7x7的迷宫定义成了一维numpy数组,
np.argwhere在一维数组上返回的是形如[[idx]]的(N,1)结构,而非二维坐标的(N,2)结构,所以访问currentCoords[0,1]会触发轴1越界(因为轴1的长度只有1)。 - 类型转换错误:初始
CurrentValue是字符串"Y",后续代码试图执行int(CurrentValue),这会直接报错,无法将"Y"转为整数。 - 逻辑缺失:当前代码没有实现Dijkstra算法的核心逻辑(优先级队列、邻居遍历、距离更新),仅在循环中处理单个位置,无法完成路径搜索。
修复方案与代码示例
- 将迷宫转为二维数组:用
reshape(7,7)把一维数组转换成7行7列的二维结构,这样np.argwhere会返回(row, col)形式的二维坐标。 - 重构距离记录逻辑:用单独的距离矩阵记录各节点到终点的距离,避免直接修改迷宫字符串,同时解决类型转换问题。
- 补全Dijkstra核心逻辑:使用优先级队列(heapq)处理节点,遍历上下左右四个有效邻居,更新最短距离。
修复后的代码:
import numpy as np import heapq # 定义7x7迷宫,转为二维数组 maze = np.array([ "X", "_", "_", "_", "_", "Z", "_", "_", "Z", "Z", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "_", "_", "_", "_", "_", "_", "Z", "_", "Z", "Z", "_", "_", "_", "Z", "_", "Z", "_", "_", "_", "_", "Z", "_", "_", "_", "Y" ]).reshape(7, 7) # 初始化距离矩阵,所有节点设为无穷大 distance = np.full(maze.shape, np.inf) # 找到起点X和终点Y的坐标 start_pos = tuple(np.argwhere(maze == "X")[0]) end_pos = tuple(np.argwhere(maze == "Y")[0]) # 终点距离设为0 distance[end_pos] = 0 # 优先级队列,存储(距离, 坐标),从终点开始反向搜索 heap = [] heapq.heappush(heap, (0, end_pos)) # 定义四个方向:上下左右 directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] while heap: current_dist, (row, col) = heapq.heappop(heap) # 如果到达起点,停止搜索 if (row, col) == start_pos: break # 如果当前记录的距离大于已找到的更短距离,跳过 if current_dist > distance[row, col]: continue # 遍历四个邻居 for dr, dc in directions: new_row = row + dr new_col = col + dc # 检查邻居是否在迷宫范围内 if 0 <= new_row < 7 and 0 <= new_col < 7: # 跳过障碍物Z if maze[new_row, new_col] == "Z": continue # 计算新距离 new_dist = current_dist + 1 # 如果新距离更短,更新并加入队列 if new_dist < distance[new_row, new_col]: distance[new_row, new_col] = new_dist heapq.heappush(heap, (new_dist, (new_row, new_col))) # 输出距离矩阵,起点的距离就是最短路径长度 print("最短路径长度:", distance[start_pos]) # 也可以打印距离矩阵查看各点到终点的距离 print("距离矩阵:\n", distance)
内容的提问来源于stack exchange,提问作者EMarb187
相关产品推荐
相关产品推荐

