【发布时间】:2022-01-17 19:38:42
【问题描述】:
我正在尝试使用贪心算法解决具有限制的 TSP。我现在可以在跑步过程中得到正确的路线,但我不知道当我得到答案时如何准确地停止循环。这是我的主要代码。
while repeat_number < nodes_number :
best_path = 999999999
for i in range(nodes_number):
if total_distance + distance[city_visited[-1]][i] <= 20000:
if i not in city_visited and distance[city_visited[-1]][i] != 0 and distance[city_visited[-1]][i] <= best_path:
best_path = distance[city_visited[-1]][i]
next_city = i
city_visited.append(next_city)
total_distance = total_distance + best_path
repeat_number = repeat_number + 1
通过这段代码,我可以找到重复次数为19时的最佳解决方案 enter image description here
但是,循环会继续,导致最终结果错误。因此,我想知道一旦我得到答案,如何停止这个循环。希望得到您的帮助;非常感谢你们!
【问题讨论】:
标签: python python-2.7 loops