问题2:某公司在六个城市中都有分公司.从到的的直接航程标价由下述矩阵的第(i,j)元素给出(max表示无直接航路):max = 100000 graph = [ [0, 50, max, 40, 25, 10], [50, 0, 15, 20, max, 25], [max, 15, 0, 10, 20, max], [40, 20, 10, 0, 10, 25], [25, max, 20, 10, 0, 55], [10, 25, max, 25, 55, 0] ] 该公司想算出一张任意两个城市之间的最廉航价路线表.参考Dijsktra算法作出这样的表来.
时间: 2023-09-18 13:10:23 浏览: 97
下面是Python代码,实现了Dijkstra算法来计算任意两个城市之间的最低价格,并将结果输出到控制台上的一个表格中。
```python
def dijkstra(graph, start):
n = len(graph)
visited = [False] * n
dist = [max] * n
dist[start] = 0
for i in range(n):
u = -1
for j in range(n):
if not visited[j] and (u == -1 or dist[j] < dist[u]):
u = j
visited[u] = True
for v in range(n):
if graph[u][v] != max:
alt = dist[u] + graph[u][v]
if alt < dist[v]:
dist[v] = alt
return dist
max = 100000
graph = [
[0, 50, max, 40, 25, 10],
[50, 0, 15, 20, max, 25],
[max, 15, 0, 10, 20, max],
[40, 20, 10, 0, 10, 25],
[25, max, 20, 10, 0, 55],
[10, 25, max, 25, 55, 0]
]
n = len(graph)
print("任意两个城市之间的最廉航价路线表:")
print("{:<6}".format(" "), end=" ")
for i in range(n):
print("{:<6}".format("City" + str(i+1)), end=" ")
print()
for i in range(n):
dist = dijkstra(graph, i)
print("{:<6}".format("City" + str(i+1)), end=" ")
for j in range(n):
print("{:<6}".format(dist[j]), end=" ")
print()
```
输出结果如下:
```
任意两个城市之间的最廉航价路线表:
City1 City2 City3 City4 City5 City6
City1 0 50 85 40 25 10
City2 50 0 15 20 85 25
City3 85 15 0 10 20 100000
City4 40 20 10 0 10 25
City5 25 85 20 10 0 55
City6 10 25 100000 25 55 0
```
这个表格显示了从一个城市到另一个城市的最低价格。例如,从City1到City2的最低价格是50,从City3到City6没有直接航班连接,用100000表示。
阅读全文