import heapq

def FindPath(nodeCount, costs, startIndex, endIndex):
    # 创建距离数组,初始时起始节点到自身的距离为0,其他节点的距离设为无穷大
    distances = [float('inf')] * nodeCount
    distances[startIndex] = 0
    
    # 创建已访问集合,记录已经找到最短路径的节点
    visited = set()
    
    # 创建优先队列,用于选择距离起始节点最近且尚未被访问的节点进行访问
    pq = [(0, startIndex)]  # 优先队列中的元素为 (距离, 节点序号)
    
    # 创建路径数组,用于记录最短路径
    path = [-1] * nodeCount
    
    while pq:
        # 从优先队列中取出距离起始节点最近的节点进行访问
        dist, node = heapq.heappop(pq)
        
        # 如果该节点已经被访问过,则跳过
        if node in visited:
            continue
        
        # 将该节点标记为已访问
        visited.add(node)
        
        # 遍历该节点的邻居节点
        for neighbor, weight in enumerate(costs[node]):
            # 如果该邻居节点未被访问,并且通过当前节点到达该邻居节点的距离更短,则更新距离数组和路径数组
            if neighbor not in visited and dist + weight < distances[neighbor]:
                distances[neighbor] = dist + weight
                heapq.heappush(pq, (dist + weight, neighbor))
                path[neighbor] = node
    
    # 根据路径数组构建最短路径
    wayList = []
    while endIndex != -1:
        wayList.append(endIndex)
        endIndex = path[endIndex]
    
    # 将最短路径逆序后返回
    return wayList[::-1]

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐