交通图中两地之间的最短路径状态图搜索策略实验代码
时间: 2024-02-12 09:07:37 浏览: 105
图的最短路径 数据结构实验代码
以下是一个基于Dijkstra算法的最短路径状态图搜索策略实验代码示例,可以用于求解交通图中两地之间的最短路径问题:
```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}
# 将起点加入堆中,开始搜索
heap = [(0, start)]
while heap:
# 取出距离最小的节点
current_dist, current_node = heapq.heappop(heap)
# 如果当前节点已经访问过,则跳过
if current_dist > dist[current_node]:
continue
# 遍历当前节点的邻居
for neighbor, weight in graph[current_node].items():
# 计算新的距离
new_dist = current_dist + weight
# 如果新的距离比原来的距离更短,则更新
if new_dist < dist[neighbor]:
dist[neighbor] = new_dist
previous[neighbor] = current_node
heapq.heappush(heap, (new_dist, neighbor))
# 回溯路径
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)
```
该代码使用了堆优化的Dijkstra算法来求解最短路径。其中,`graph`变量表示图的邻接表,`start`和`end`变量分别表示起点和终点。该算法会返回一条最短路径以及对应的距离。
阅读全文