赞
踩
解释:
该算法用于需要计算所有的解,并从中找到最短的那一个
与狄克斯特拉算法不同的是:这里只输入了狄克斯特拉算法里面的cost
# 输入旅行表信息 distance = {} distance['ab'] = distance['ba'] = 10 distance['ac'] = distance['ca'] = 12 distance['ad'] = distance['da'] = 16 distance['bc'] = distance['cb'] = 12 distance['bd'] = distance['db'] = 10 distance['cd'] = distance['dc'] = 8 def search2(data, will_del, end, count): lowest_distance = 1000 lowest_distance_name = None for i in distance.keys(): if i[0] == data and i[-1] != will_del: # 选择出发打头的路线并且剔除返回路线 if distance[i] < lowest_distance: lowest_distance = distance[i] lowest_distance_name = i print(lowest_distance_name[-1]) print("|") data = lowest_distance_name[-1] will_del = lowest_distance_name[0] count += 1 if count > end: # 循环结束标志,即回到出发点 print('Have a good day') else: search2(data, will_del, end, count) def main(): data = input('请自定义起始出发点:') counts = input("请输入旅行地点个数:") print("最佳旅行路线如下:") print(data) print("|") count = eval(counts) # 地点数 end = count + (count - 1) search2(data, "N1", end, count) # 输入N1,所有路线全是英文字母,1有利于首次剔除 if __name__ == '__main__': main()
结果展示:
请自定义起始出发点:c 请输入旅行地点个数:4 最佳旅行路线如下: c | d | b | a | c | Have a good day
添加删除,使得再次循环次数减少
该方法可以在大量路线循环时减少运算时间,但是结果只能趋近于最优解(如该代码中的出发地b),这也是贪婪算法的弊端所在
# 输入旅行表信息 distance = {} distance['ab'] = distance['ba'] = 10 distance['ac'] = distance['ca'] = 12 distance['ad'] = distance['da'] = 16 distance['bc'] = distance['cb'] = 12 distance['bd'] = distance['db'] = 10 distance['cd'] = distance['dc'] = 8 def search(data, will_del, end, count): lowest_distance = 1000 lowest_distance_name = None for i in list(distance.keys()): if i[0] == data and i[-1] != will_del: # 选择出发打头的路线并且剔除返回路线 if distance[i] < lowest_distance: lowest_distance = distance[i] lowest_distance_name = i del distance[i] # 删除已过滤的路线,使得下次循环次数减少 del distance[i[::-1]] print(" " + lowest_distance_name[-1]) print(" |") data = lowest_distance_name[-1] will_del = lowest_distance_name[0] count += 1 if count > end: # 循环结束标志,即回到出发点 print('回到出发点:') print(' |') else: search(data, will_del, end, count) def main(): data = input('请自定义起始出发点:') counts = input("请输入旅行地点个数:") print("最佳旅行路线:") print(' ' + data) print(" |") count = eval(counts) # 地点数 end = count + (count - 2) search(data, "N1", end, count) # 输入N1,所有路线全是英文字母,1有利于首次剔除 print(" " + data) print(" |") print("Have a good day") if __name__ == '__main__': main()
结果展示:
请自定义起始出发点:c 请输入旅行地点个数:4 最佳旅行路线: c | d | b | a | 回到出发点: | c | Have a good day Process finished with exit code 0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。