完整代码
import os
import numpy
import pandas as pd
import numpy as np
def dijkstra(filepath):
# 读取数据
read_data = pd.read_csv(filepath)
# 存入数组
data = np.array(read_data)
# 遍历节点个数
v_max = max(np.max(data, axis=0)[1], np.max(data, axis=0)[2])
v = v_max + 1
# 初始化
# 原点到各点的最短路长
path_length = [float('inf') for i in range(v)]
path_length[0] = 0
# 各点的前置节点
pr = [-1 for i in range(v)]
# 初始节点
u = 0
# 已遍历节点
s = list()
s.append(u)
# 遍历次数i
i = 0
# 邻接矩阵
D = [[float('inf')] * v for _ in range(v)]
for n in range(len(data)):
D[data[n][1]][data[n][2]] = data[n][3]
# 路径列表
path = [[] for i in range(v)]
path[0].append(u)
# 路长列表
lr = numpy.zeros(v, dtype='float')
for n in range(v):
lr[n] = numpy.Inf
lr[0] = 0
while i < (v - 1):
for j in range(v):
if j not in s:
if path_length[j] > (path_length[u] + D[u][j]):
path_length[j] = path_length[u] + D[u][j]
pr[j] = u
lr[j] = path_length[u] + D[u][j]
i = i + 1
temp = float('inf')
temp_index = float('inf')
for k in range(v):
if k not in s:
if temp > path_length[k]:
temp = path_length[k]
temp_index = k
u = temp_index
s.append(u)
path[u].extend(path[pr[u]])
path[u].append(u)
if os.path.exists('result.xlsx'):
os.remove('result.xlsx')
output = open('result.xlsx', 'w', encoding='gbk')
output.write('v\t从原点到点v的最短路径\t路长值\n')
for n in range(1, v):
output.write(str(n))
output.write('\t')
output.write(str(path[n]))
output.write('\t')
output.write(str(lr[n]))
output.write('\n')
output.close()
return path
if __name__ == '__main__':
dijkstra("data_new.csv")
源数据的格式:序号-源节点-目的节点-边长值
最后输出一个.xlsx文件 并且返回路径列表