本题要求在给定的图G和启发函数H上,基于A*搜索算法,寻找一条从A到K的路径
函数接口定义:
def pick_from_Astar(graph, fringe, heuristic)
其中 frienge
是边缘结点集合, heuristic
是启发函数。要求基于A*搜索算法,使用启发函数heuristic
从边缘集合中frienge
中选取一个待扩展的结点,并返回该结点及其对应的评估代价。题目中的启发函数即为在main函数中定义的H。
裁判测试程序样例:
def loop_test(n):
for i in range(len(n)-1):
if n[i] == n[-1]:
return True
return False
def goal_test(n):
if(n[-1] == 'K'):
return True
else:
return False
def extend(fringe, n, graph):
state = n[-1]
for item in graph[state]:
node = []
for j in n:
node.append(j)
node.append(item)
fringe.append(node)
def AstarSearch(G,H):
root = ['A']
F = []
F.append(root)
i = 0
while len(F)>0 and i < 100:
i = i + 1
n,cost = pick_from_Astar(G, F, H)
print("processing {}, cost = {} ".format(n,cost))
if loop_test(n):
print("{}, containing loop, cutted".format(n))
continue
if goal_test(n):
print("{}, found goal, cost = {}, exit".format(n, cost))
break
extend(F, n, G)
if __name__ == "__main__":
G = {'A':{'B':5, 'D':3, 'E':6},
'B':{'A':5,'C':5},
'C':{'B':5},
'D':{'A':3,'F':4},
'E':{'A':6,'G':3,'I':7,'H':4},
'F':{'D':4,'G':4},
'G':{'F':4,'E':3,'H':3,'K':5},
'H':{'E':4,'G':3,'J':7},
'I':{'E':7,'J':5},
'J':{'H':7,'K':3},
'K':{'G':5,'J':3,'L':6},
'L':{'K':6}}
H = {'A':13, 'B':10, 'C':6, 'D':12, 'E':7, 'F':8,
'G':5, 'H':3, 'I':6, 'J':3, 'K':0, 'L':6}
AstarSearch(G,H)
/* 请在这里填写答案 */
输入样例:
无输入
输出样例:
在这里给出相应的输出。例如:
processing ['A'], cost = 13
processing ['A', 'E'], cost = 13
processing ['A', 'E', 'H'], cost = 13
processing ['A', 'E', 'G'], cost = 14
processing ['A', 'E', 'G', 'K'], cost = 14
['A', 'E', 'G', 'K'], found goal, cost = 14, exit
示例:
def pick_from_Astar(graph, fringe, heuristic):
min = 99
j = 0
for item in fringe:
g_cost = 0
i = 1
while i < len(item):
g_cost += graph[item[i - 1]][item[i]]
i += 1
h_cost = heuristic[item[-1]]
cost = g_cost + h_cost
if cost <= min:
min = cost
best_node = item
a = j
j += 1
del fringe[a]
return best_node, min