如何实现弗洛伊德算法?

时间:2019-05-06 14:52:14

标签: python floyd-warshall

我必须在Python中实现Floyd算法。

我必须使用此代码模板。 练习中给出了邻接矩阵,但是我必须将其转换为双矩阵,如下所示。最后,需要在双矩阵上执行弗洛伊德算法。

我现在的主要问题是将邻接矩阵转换为双矩阵,该双矩阵包含距离和上一个结。

import math
import pprint as pp

def createBiMatrix(mat):


bimatrix = [] 


pass

return bimatrix



def updateForNode(bimat, node):

pass;




return bimat



def determinePath(bimat, start, end):


recursionStep(bimat, start, end)

print(end)


def recursionStep(bimat, start, end):

pass

return


if __name__ == "__main__":

matsize = 5

mat = [matsize * [math.inf] for i in range(matsize)]
mat[0][0] = 0
mat[0][1] = 2
mat[0][2] = 10
mat[1][1] = 0
mat[1][2] = 3
mat[1][3] = 12
mat[2][0] = 10
mat[2][1] = 3
mat[2][2] = 0
mat[2][4] = 1
mat[3][1] = 12
mat[3][3] = 0
mat[4][2] = 1
mat[4][3] = 6
mat[4][4] = 0

bim = createBiMatrix(mat)
pp.pprint(bim)


for i in range(matsize):
    bim = updateForNode(bim, i)
    print("Step " + str(i) + ":")
    pp.pprint(bim)



start = 0
end = 3
print("shortest path (" + str(start) + " nach " + str(end) + "):")
determinePath(bim, start, end)

1 个答案:

答案 0 :(得分:0)

假设bimatrix是一个列表,该索引在索引i上存储到顶点i和先前顶点的最短路径

createBiMatrix(mat):
  bimatrix = [(math.inf, None) for _ in range(len(mat))]

  for from in range(len(mat)):
    for to in range(len(mat[0])):
      if mat[from][to] < bimatrix[to][0]:
        bimatrix[to] = (mat[from][to], from)
  return bimatrix