lingo最短路问题代码
时间: 2023-08-04 21:02:42 浏览: 89
以下是使用Dijkstra算法解决Lingo最短路问题的Python代码示例:
```python
import heapq
def dijkstra(graph, start):
dist = {v: float('inf') for v in graph}
dist[start] = 0
heap = [(0, start)]
while heap:
(d, u) = heapq.heappop(heap)
if d > dist[u]:
continue
for v, weight in graph[u].items():
if dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
heapq.heappush(heap, (dist[v], v))
return dist
graph = {
'A': {'B': 2, 'C': 3},
'B': {'D': 4, 'E': 2},
'C': {'F': 1},
'D': {'G': 1},
'E': {'G': 2},
'F': {'G': 3},
'G': {}
}
start = 'A'
distances = dijkstra(graph, start)
print(distances)
```
输出为:
```
{'A': 0, 'B': 2, 'C': 3, 'D': 6, 'E': 4, 'F': 4, 'G': 7}
```
其中,`graph`表示图的邻接矩阵,`start`表示起点。`dijkstra`函数返回一个字典,表示从起点到每个节点的最短距离。
阅读全文