代价树搜索策略求解交通图中两地之间的最短路径python实验代码
时间: 2024-02-12 21:07:45 浏览: 118
以下是一个基于代价树搜索策略的最短路径实验代码示例,可以用于求解交通图中两地之间的最短路径问题:
```python
import heapq
def dijkstra(graph, start, end):
# 初始化距离字典和前置节点字典
dist = {node: float('inf') for node in graph}
dist[start] = 0
previous = {node: None for node in graph}
# 初始化代价树
cost_tree = {node: {} for node in graph}
for neighbor, weight in graph[start].items():
cost_tree[neighbor][start] = weight
# 开始搜索
heap = [(0, start)]
visited = set()
while heap:
node_dist, node = heapq.heappop(heap)
if node == end:
break
if node in visited:
continue
visited.add(node)
for neighbor, weight in graph[node].items():
if neighbor in visited:
continue
cost = node_dist + weight
if cost < dist[neighbor]:
dist[neighbor] = cost
previous[neighbor] = node
cost_tree[neighbor] = {node: weight}
heapq.heappush(heap, (cost, neighbor))
elif cost == dist[neighbor]:
cost_tree[neighbor][node] = weight
# 回溯路径
path = []
node = end
while node is not None:
path.append(node)
node = previous[node]
path.reverse()
return path, dist[end]
# 测试代码
graph = {
'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'C': 2, 'D': 1},
'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
'E': {'C': 8, 'D': 3},
'F': {'D': 6}
}
start = 'A'
end = 'F'
path, dist = dijkstra(graph, start, end)
print("最短路径:", path)
print("最短距离:", dist)
```
该代码使用了代价树搜索策略来求解最短路径。其中,`graph`变量表示图的邻接表,`start`和`end`变量分别表示起点和终点。该算法会返回一条最短路径以及对应的距离。
阅读全文