#coding=utf-8
#输出路径结果
wayList = []
#在该方法中完成寻路算法,并将包含起点和终点在内的路径序号(int类型)按照顺序放入wayList数组中
# nodeCount:抽象图中的节点总数量
# costs:二维权值数组,表示序号0~nodeCount节点之间的权值关系,元素为int类型,比如使用data.costs[0][2]获得第一个节点和第三个节点之间的权值
# startIndex:起始节点序号
# endIndex:终点节点序号
def FindPath(nodeCount, costs, startIndex, endIndex):
###### Begin ######
def dijkstra(graph, start, end):
# 初始化距离列表,用于记录起点到各个节点的距离
distance = [float('inf')] * nodeCount
distance[start] = 0 # 起点到起点的距离为0
# 初始化已访问节点列表,用于记录已经确定最短路径的节点
visited = [False] * nodeCount
# 初始化路径列表,用于记录路径
path = [[] for _ in range(nodeCount)]
# 找到起点到终点的最短路径
for _ in range(nodeCount):
# 找到未访问节点中距离最短的节点
min_distance = float('inf')
min_index = -1
for i in range(nodeCount):
if not visited[i] and distance[i] < min_distance:
min_distance = distance[i]
min_index = i
if min_index == -1:
break # 如果不存在未访问的节点,则跳出循环
visited[min_index] = True # 将最短路径节点标记为已访问
# 更新起点到各个节点的距离和路径
for i in range(nodeCount):
if not visited[i] and graph[min_index][i] > 0:
new_distance = distance[min_index] + graph[min_index][i]
if new_distance < distance[i]:
distance[i] = new_distance
path[i] = path[min_index] + [min_index]
return path[end] + [end] # 返回起点到终点的最短路径
# 构建邻接矩阵,用于表示节点之间的距离
graph = [[0] * nodeCount for _ in range(nodeCount)]
for i in range(nodeCount):
for j in range(nodeCount):
graph[i][j] = costs[i][j] if i != j else 0
# 使用 Dijkstra 算法求解最短路径
wayList.extend(dijkstra(graph, startIndex, endIndex))
###### end ######
return wayList
第2关:复杂山路物资运送:配置地图
最新推荐文章于 2024-05-19 23:31:32 发布