T标号排序的Dijkstra算法代码,输出最短路径和成本
时间: 2024-04-28 19:24:45 浏览: 15
以下是使用T标号排序的Dijkstra算法代码,该代码输出最短路径和成本:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典和T标号数组
distance = {node: float('inf') for node in graph}
t_label = [(0, start)] # (距离, 节点)
distance[start] = 0
path = {} # 记录最短路径
while t_label:
# 选择当前距离最小的节点
current_distance, current_node = heapq.heappop(t_label)
if current_distance > distance[current_node]:
continue
for neighbor, weight in graph[current_node].items():
# 计算新的距离
new_distance = current_distance + weight
if new_distance < distance[neighbor]:
# 更新距离和路径
distance[neighbor] = new_distance
path[neighbor] = current_node
heapq.heappush(t_label, (new_distance, neighbor))
return distance, path
def shortest_path(graph, start, end):
distances, paths = dijkstra(graph, start)
if end not in distances:
return None, None
# 构建最短路径
shortest_path = []
node = end
while node != start:
shortest_path.append(node)
node = paths[node]
shortest_path.append(start)
return list(reversed(shortest_path)), distances[end]
# 测试示例
graph = {
'A': {'B': 5, 'C': 2},
'B': {'A': 5, 'C': 1, 'D': 3},
'C': {'A': 2, 'B': 1, 'D': 2},
'D': {'B': 3, 'C': 2}
}
start_node = 'A'
end_node = 'D'
path, cost = shortest_path(graph, start_node, end_node)
print("最短路径:", path)
print("最短路径成本:", cost)
```
该代码在使用T标号排序的Dijkstra算法的基础上,添加了最短路径的计算。通过调用`shortest_path`函数,可以获取从起始节点到目标节点的最短路径和对应的成本。最短路径以列表形式返回,成本作为额外的返回值。以上代码仅为示例,你可以根据自己的需求进行修改和扩展。