我試圖在給定約束路徑必須總距離小於某個參數(比方說1000)的加權圖上找到最短路徑。如何在圖上找到滿足約束條件的最短路徑
我試過以下,但我不知道爲什麼我的代碼是錯誤的。
def directedDFS(digraph, start, end, maxTotalDist):
visited = []
if not (digraph.hasNode(start) and digraph.hasNode(end)):
raise ValueError('Start or end not in graph.')
path = [str(start)]
if start == end:
return path
shortest = None
for node in digraph.childrenOf(start):
if (str(node) not in visited):
visited = visited + [str(node)]
firststep_distance = digraph.childrenOf(start)[node][0]
firststep_outer_distance = digraph.childrenOf(start)[node][1]
if (firststep_distance <= maxTotalDist):
newPath = directedDFS(digraph, node, end, maxTotalDist-firststep_distance)
if newPath == None:
continue
if (shortest == None or TotalDistance(digraph,newPath) < TotalDistance(digraph,shortest)):
shortest = newPath
if shortest != None:
path = path + shortest
else:
path = None
return path
另一件事是,我不希望比較基於從給定節點開始的路徑的距離,而是基於整個路徑從原來的起點的距離。我不知道在這裏做這件事的最好方法。
你的意思是跳數或距離最短(後者是微不足道的,所以我猜這是前者)? – NPE 2011-05-06 16:12:07
您是否試圖找到包含總路徑成本(其邊緣權重之和)小於1000的最少邊的路徑? – 2011-05-07 03:15:06