1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import random import time import numpy as np import sys
def random_matrix(vex_num): ''' 随机图顶点矩阵生成器 输入:顶点个数,即矩阵维数 ''' data_matrix =[ [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] ]
return data_matrix def floyd(data_matrix, vex_num):
dist_matrix = data_matrix path_matrix = [[1, 2, 3, 4, 5, 6]] * 6
for k in range(vex_num): for i in range(vex_num): for j in range(vex_num): temp = dist_matrix[i][k] + dist_matrix[k][j] if dist_matrix[i][j] > temp: dist_matrix[i][j] = temp path_matrix[k][i] = path_matrix[i][j] return dist_matrix, path_matrix
if __name__ == '__main__':
vex_num = 6 data_matrix = random_matrix(vex_num) dist_matrix , path_matrix = np.array(floyd(data_matrix, vex_num)) for i in range(vex_num): for j in range(vex_num): print ( str(i) + '----->' + str(j) + ' shortest_path distance is : ', dist_matrix[i][j])
print(path_matrix)
|