A* Search Algorithm
写在前面:第一次写博客,以后想把遇到的有意思的算法或者小知识记录下来。纯原创,部分图片来自课堂PPT,出自UCR,CS170课件。转载请声明出处。
算法简介
A* Search 是一种启发式搜索算法,该算法内置一个函数来表达当前状态和目标状态的差值。举个栗子,8-puzzle问题(一个游戏,目标是将对应数字的版块放到对应位置)。当前状态是下图
目标状态:
如果我们以两个状态有多少不符合启发函数,那么这里的启发函数的值是
1(PS:这里我们排除了空白格,图中当前态和目标态就一个‘8’不同)
接下来会详细介绍A算法并以8-puzzle游戏左右一个例子来说明该算法,在引入A search前,我会先简单介绍两个算法,Uniform Cost Search和Hill climbing Search。启发函数选择的是Manhattan距离,详解看下图。(h(n)就是启发函数)
先说说Hill climbing Search,该算法也是一种启发式搜索算法,思路很简单,直接使用Manhattan距离。在下面的例子中,这个算法运行的很好。(h(n)是启发函数)
这个算法运行的很快,可是会遇到问题。有时候该算法在一些状态会陷入找不到解的状态
另一种Uniform Cost Search算法,该算法更简单每次在拓展节点的时候,拓展最廉价的点(该点的耗费是到这个点的路径的累积消耗,拓展累积消耗最小的点)。该算法运行效率较低,但是可以保证每次找到一个解。
背景介绍完毕。接下来进入A*算法,这个算法结合了Uniform Cost Search和Hill climbing Search。将到达该节点的累积消耗g(n)和该节点到达目标节点的差h(n)作为启发函数
下图是一个A算法的例子:这是一个迷宫问题,初始状态是粉色的点,目标状态是蓝色的点。将粉点移动到蓝点即可。图中的树说明了用A树的搜索过程。H(n)依然使用Manhattan距离
说到这,A算法的基本概念已经介绍完毕。一下附上A算法的实现代码(Python)。以解决8-puzzle问题作为背景。
实现代码
import numpy as np
import Queue
import copy
DEFAULT_PUZZLE = np.array([1,2,3,4,8,0,7,6,5]).reshape((3,3))
GOAL_STATE = np.array([1,2,3,4,5,6,7,8,0]).reshape((3,3))
STATE_TABLE = dict() # store the state already check
class Node():
'''
:description: define the Node class
'''
def __init__(self,puzzle,depth,total_cost,blank_index_i,blank_index_j):
self.puzzle = puzzle
self.depth = depth
self.total_cost = total_cost
self.blank_index_i = blank_index_i
self.blank_index_j = blank_index_j
def get_depth(self):
return self.depth
def get_puzzle(self):
return self.puzzle
def get_total_cost(self):
return self.total_cost
def get_blank_index_i(self):
return self.blank_index_i
def get_blank_index_j(self):
return self.blank_index_j
def __lt__(self, other):
return self.total_cost < other.total_cost
def Init_input_puzzle():
'''
:description:
Initializing the input puzzle matrix, and choose the algorithm
:input: None
:return:
puzzle: the puzzle need to solved
key: the choice of algorithm
blank_index_i : the blank block index
blank_ind