以下是一个使用SimpleAI库中的A*搜索算法的示例程序,用于找到从起始位置到目标位置的最短路径。
from simpleai.search import astar, SearchProblemclass GridProblem(SearchProblem):def __init__(self, initial_state, goal_state):self.initial_state = initial_stateself.goal_state = goal_statedef actions(self, state):actions = []x, y = stateif x > 0:actions.append((x - 1, y))if x < 4:actions.append((x + 1, y))if y > 0:actions.append((x, y - 1))if y < 4:actions.append((x, y + 1))return actionsdef result(self, state, action):return actiondef is_goal(self, state):return state == self.goal_statedef heuristic(self, state):x1, y1 = statex2, y2 = self.goal_statereturn abs(x1 - x2) + abs(y1 - y2)initial_state = (0, 0)
goal_state = (3, 4)problem = GridProblem(initial_state, goal_state)
result = astar(problem)path = [action for action, _ in result.path()]
print("Path:", path)
print("Path Cost:", result.cost)
在上面的示例中,GridProblem
类继承了simpleai.search.SearchProblem
,并实现了必要的方法。actions
方法返回当前状态下可行的动作,result
方法返回从当前状态应用动作之后的结果状态,is_goal
方法检查是否达到目标状态,heuristic
方法返回当前状态与目标状态之间的估计距离。
创建GridProblem
对象时,传入起始状态和目标状态。然后将问题对象传递给astar
函数,该函数使用A*算法来搜索最短路径。最后,打印出找到的路径和路径的总成本。
请注意,上面的示例中使用的是一个简单的二维网格问题,您可以根据实际问题灵活地定义自己的问题类。