python - 我一直在用我自己的例子在 python 中练习星搜索算法,但是我的算法的答案是错误的
问题描述
树节点与启发式一起显示在图像中:https : //imgur.com/Fa9MgP3。
def astaralgo():
global tree, heuristic
openedlist = [['A', 390]]
closedlist = []
#Finding the first visited node and the rest
while True:
fn = [i[1] for i in openedlist]
chosen_index = fn.index(min(fn))
node = openedlist[chosen_index][0]
closedlist.append(openedlist[chosen_index])
del openedlist[chosen_index]
if closedlist[-1][0] == 'Z':
break
for item in tree[node]:
if item[0] in [closedlist_item[0] for closedlist_item in closedlist]:
continue
cost.update({item[0]: cost[node] + item[1]})
fn_node = cost[node] + heuristic[item[0]] + item[1]
temp = [item[0], fn_node]
openedlist.append(temp)
#Optimal path search
trace_node = 'Z'
optimal_path = ['Z']
for i in range(len(closedlist)-2, -1, -1):
check_node = closedlist[i][0]
if trace_node in [children[0] for children in tree[check_node]]:
children_costs = [temp[1] for temp in tree[check_node]]
children_nodes = [temp[0] for temp in tree[check_node]]
if cost[check_node] + children_costs[children_nodes.index(trace_node)] == cost[trace_node]:
optimal_path.append(check_node)
trace_node = check_node
optimal_path.reverse()
return closedlist, optimal_path
这是它的代码。一切正常,但答案是错误的。输出如下
Nodes visited with the optimal path: [['A', 390], ['D', 390], ['C', 396], ['F', 405], ['G', 414], ['B', 435], ['F', 448], ['J', 453], ['Z', 447]]
Chosen Optimal path from A to Z: ['A', 'D', 'G', 'J', 'Z']
但这不是最佳路径。
解决方案
推荐阅读
- c# - 在 MVC API 中提供授权和未授权的端点(路由?)
- sql - 如何按字母顺序构建连接字符串?
- c# - 为什么“statusQueryGetUri”中的“runtimeStatus”没有在计时器完成后立即设置?
- javascript - 按位打包/解包 - 任意值的通用解决方案
- postgresql - Entity Framework Core 设置 ID 以从序列中获取值
- logging - 限制 Kubernetes 中的日志
- laravel - 特定路由调用上的 Laravel 502 代理错误
- python - 我的程序第 481 行有问题,它说语法错误,但语法似乎很好
- c# - 显示 Spritesheet 的帧
- javascript - 如何使用 AWS CDK 查找现有的 ApiGateway