【发布时间】:2019-07-09 15:44:44
【问题描述】:
我需要使用边的权重找到从一个给定节点到另一个节点的最短距离。我已将以下图表存储为字典: A visual representation of the graph
我尝试过使用递归方法,但到目前为止我似乎失败了。 这是我正在使用的字典:
towns = {'kendal': [['penrith', 28], ['milnthorpe', 8], ['barrow', 35]],
'penrith': [['kendal', 28]],
'barrow': [['kendal', 35], ['milnthorpe', 31]],
'milnthorpe': [['kendal', 8], ['barrow', 31], ['lancaster', 14]],
'lancaster': [['milnthorpe', 14]]
}
用户输入开始和结束节点:
places = ['kendal', 'penrith', 'barrow', 'milnthorpe', 'lancaster']
from_town = ''
while from_town not in places:
from_town = input('Where are you going from?').lower()
to_town = ''
while to_town not in places:
to_town = input('Where are you going to?').lower()
然后运行下面的代码,它很容易与直接连接到起始节点的节点一起工作,否则,递归继续并且不会停止。
routes = []
def get_route(start, finish):
others = []
for x in range(len(towns[start])):
if towns[start][x][0] == finish:
routes.append(towns[start][x][1])
else:
if towns[start][x][0] not in others:
others.append(towns[start][x][0])
for y in range(len(others)):
get_route(others[y], to_town)
get_route(from_town, to_town)
routes.sort()
print(routes[0], 'miles')
我知道我还没有停止递归的方法,但我需要让程序列出所有可能的路线。
【问题讨论】:
-
你为什么不使用networkx库?
-
@CorentinLimier 抱歉,我不知道这个库,我教给我的伙伴也不知道,所以我需要这个尽可能简单,但感谢您的回复.
-
不相关 - 但是:为什么
for x in range(len(towns[start])):而不是for town,distance in towns[start]:等等。 -
@PatrickArtner 谢谢,我会用它来代替
-
@PatrickArtner
for town,distance in towns[start]:实际上在做什么?