保存最短路径 VS 计算最短路径

时间:2021-01-27 06:00:58

标签: python dictionary memory shortest-path execution-time

我有一个 n 节点图,在我的整个函数中,我使用从一个节点到另一个节点的最短路径,我可能需要多次使用相同的路径。 我是否应该像这样在字典中保存所有节点组合的最短路径:

shortest_paths = {}
cells = graph.keys() # graph is a dictionary which represents the graph
for cell_o in cells:
   print(cell_o,'/',len(graph))
   for cell_d in cells:
      shortest_paths[(cell_o, cell_d)] = compute_shortest_path(cell_o, cell_d, graph)

并在函数的任何位置访问字典以查找从 cell1cell2 的路径,如下所示:

path = shortest_paths[(cell1, cell2)]

或者我应该在每次需要时像这样计算最短路径:

path = compute_shortest_path(cell1, cell2, graph)

为了优化执行时间,我应该做出什么选择?这个决定是否应该基于节点数 (n)、节点连接数 (n)、我需要函数中最短路径的次数、我的计算机规格?< /p>

0 个答案:

没有答案
相关问题