基于A*算法的路径搜索

本题要求在给定的图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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值