出于練習的原因,我正在研究 Advent of Code 2015,但我被困在了第 9 天。目標是找到最短距離,同時訪問圖中的每個位置一次。每個點都直接相互連接,并且終點必須與起點不同。我已經制定了解決方案,但最終值不正確,并且我沒有看到根本問題。首先,我創建一個包含位置和距離的圖形對象。然后,我將位置的每個排列收集到一個列表中,然后查找并總結每個排列的距離。最后,我打印出最小距離值,這就是練習的解決方案。代碼:from collections import defaultdictfrom itertools import permutationswith open("input.txt") as file:? ? input_ = file.read().split("\n")[:-1]class Graph():? ? def __init__(self):? ? ? ? self.edges = defaultdict(list)? ? ? ? self.weights = {}? ??? ? def add_edge(self, from_node, to_node, weight):? ? ? ? self.edges[from_node].append(to_node)? ? ? ? self.edges[to_node].append(from_node)? ? ? ? self.weights[(from_node, to_node)] = weight? ? ? ? self.weights[(to_node, from_node)] = weightgraph = Graph()edges = [(i.split()[0], i.split()[2], int(i.split()[-1])) for i in input_]for edge in edges:? ? graph.add_edge(*edge)? ??loc_set = set([i[0] for i in edges])routes = list(permutations(loc_set, len(loc_set)))dists = []for i in routes:? ? print(i)? ? dist_temp = []? ? for k in range(len(i))[1:]:? ? ? ? dist_temp.append(graph.weights[(i[k-1], i[k])])? ? dists.append(sum(dist_temp))? ? print(dist_temp)? ? print(sum(dist_temp))? ??print(min(dists))獲得無效值后,我手動檢查了一些排列及其相應的距離,因此在代碼中打印出來。輸入(將其復制并粘貼到記事本并將其另存為 input.txt 對于我的代碼應該可以正常工作):Faerun to Tristram = 65Faerun to Tambi = 129Faerun to Norrath = 144Faerun to Snowdin = 71Faerun to Straylight = 137Faerun to AlphaCentauri = 3Faerun to Arbre = 149Tristram to Tambi = 63Tristram to Norrath = 4Tristram to Snowdin = 105Tristram to Straylight = 125Tristram to AlphaCentauri = 55Tristram to Arbre = 14Tambi to Norrath = 68Tambi to Snowdin = 52Tambi to Straylight = 65Tambi to AlphaCentauri = 22Tambi to Arbre = 143我非常確定,這個問題有更完善的解決方案,并且我愿意接受建議,因為我只是一個業余愛好者。然而,如果我們能夠解決我的方法的缺點并使其正常工作,我會非常高興。
1 回答

慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
我發現了錯誤!事實證明,該方法是有效的,我只是在定義位置集時粗心了。
我假設每個位置在指令字符串的開頭至少出現一次。然而,一個位置(“Arbre”)僅出現在指令末尾。因此,圖表不完整,因此輸出錯誤。
作為快速修復,我按以下方式修改了代碼:
loc_set?=?set([i[0]?for?i?in?edges])
到
loc_set?=?list(set([i[0]?for?i?in?edges])) loc_set.append("Arbre")
另外,事實證明,順便說一句,該方法對于本次練習很有用,因為第二部分要求最長距離,可以通過最后的一行附加代碼找到最長距離:
print(max(dists))
添加回答
舉報
0/150
提交
取消