短路导航算法如何写代码
时间: 2024-03-06 14:49:32 浏览: 11
短路导航算法的代码实现可以采用Dijkstra算法或A*算法。
以下是使用Dijkstra算法实现短路导航算法的代码示例:
```python
# 定义一个函数来计算最短路径
def dijkstra(graph, start, end):
# 初始化距离字典和前驱节点字典
distance = {vertex: float('inf') for vertex in graph}
previous = {vertex: None for vertex in graph}
# 设置起点的距离为0
distance[start] = 0
# 建立一个空的优先队列
pq = []
# 将起点加入优先队列
heapq.heappush(pq, (0, start))
# 开始遍历每个节点
while pq:
# 取出当前距离最小的节点
current_distance, current_vertex = heapq.heappop(pq)
# 如果当前节点已经被访问过,则跳过
if current_distance > distance[current_vertex]:
continue
# 遍历当前节点的邻居节点
for neighbor, weight in graph[current_vertex].items():
# 计算到邻居节点的距离
distance_to_neighbor = current_distance + weight
# 如果当前距离比之前计算的距离更小,则更新距离和前驱节点
if distance_to_neighbor < distance[neighbor]:
distance[neighbor] = distance_to_neighbor
previous[neighbor] = current_vertex
heapq.heappush(pq, (distance_to_neighbor, neighbor))
# 构建路径
path = []
vertex = end
while vertex is not None:
path.append(vertex)
vertex = previous[vertex]
# 将路径反转,得到正常的顺序
path.reverse()
return path, distance[end]
```
以上代码实现了使用Dijkstra算法计算最短路径的功能,其中输入参数graph是一个字典,存储了每个节点和它的邻居节点及对应的权重。start和end分别表示起点和终点。函数返回最短路径和对应的距离。