编写外卖最短路径的代码
时间: 2023-10-21 18:24:09 浏览: 90
好的,这里提供一种基于Dijkstra算法的解法,具体实现如下:
```python
import heapq
def dijkstra(graph, start):
distances = {vertex: float('inf') for vertex in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
current_distance, current_vertex = heapq.heappop(pq)
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
def shortest_path(graph, start, end):
distances = dijkstra(graph, start)
path = []
vertex = end
while vertex != start:
path.append(vertex)
vertex = distances[vertex][1]
path.append(start)
return path[::-1]
# 测试
graph = {
'外卖店': {'A': 2, 'B': 3, 'C': 5},
'A': {'外卖店': 2, 'B': 2, 'D': 4},
'B': {'外卖店': 3, 'A': 2, 'D': 3, 'E': 4},
'C': {'外卖店': 5, 'E': 3},
'D': {'A': 4, 'B': 3, 'E': 2, 'F': 3},
'E': {'B': 4, 'C': 3, 'D': 2, 'F': 2},
'F': {'D': 3, 'E': 2}
}
start = '外卖店'
end = 'F'
shortest_path = shortest_path(graph, start, end)
print(shortest_path)
```
这里的 `graph` 表示外卖店到各个顾客之间的距离,可以根据实际情况进行修改。 `start` 表示出发点,即外卖店的位置, `end` 表示目的地,即所有顾客的位置。函数 `dijkstra` 是基于Dijkstra算法实现的最短路径计算函数,函数 `shortest_path` 则是最短路径查找函数。最后将结果打印输出即可。
阅读全文