太白发句,谓之开门见山。
代码一一如下。
# This is a program to illustrate the detail of dijkstra algorithm.
# 这里为了引入无穷大这个概念
import sys
size = 6
adjMatrix = [[0, 50, sys.maxsize, 40, 25, 10], [50, 0, 15, 20, sys.maxsize, 25], [sys.maxsize, 15, 0, 10, 20, sys.maxsize], [40, 20, 10, 0, 10, 25],
[25, sys.maxsize, 20, 10, 0, 55], [10, 25, sys.maxsize, 25, 55, 0]]
"""
这一部分是用作手动输入的代码
for i in range(size):
tempRow = []
print("Please input Row " + str(i) + " of the matrix.")
for j in range(size):
temp = int(input("Input the weight.(Use sys.maxsize to represent infinity)"))
if temp == sys.maxsize:
temp = sys.maxsize
tempRow.append(temp)
adjMatrix.append(tempRow)
"""
visited = [0 for i in range(size)] #已经访问过的节点列表,0与1表示了有与无的概念
visited[0] = 1
cityDis = adjMatrix[0] #表示与起始点的距离
routine = [[0] for i in range(size)] #存储了到各个点的最短路径
for i in range(1, size):
print(cityDis)
minDisPos = int()
minDis = sys.maxsize
for j in range(1, size):
if visited[j] == 1:
continue
if cityDis[j] < minDis:
minDisPos = j
minDis = cityDis[j]
visited[minDisPos] = 1
for j in range(1, size):
if visited[j] == 0:
if cityDis[j] > cityDis[minDisPos] + adjMatrix[minDisPos][j]: #如果新加入的点使得距离更短则刷新
cityDis[j] = cityDis[minDisPos] + adjMatrix[minDisPos][j]
routine[j].append(minDisPos)
print("Final result " + str(cityDis) + "\n" + str(routine))
输出一一如下。
[0, 50, 9223372036854775807, 40, 25, 10]
[0, 35, 9223372036854775807, 35, 25, 10]
[0, 35, 45, 35, 25, 10]
[0, 35, 45, 35, 25, 10]
[0, 35, 45, 35, 25, 10]
Final result [0, 35, 45, 35, 25, 10]
[[0], [0, 5], [0, 4], [0, 5], [0], [0]]
Process finished with exit code 0