使用AStar算法解决八数码问题

八数码问题是一个经典的搜索问题,本文将介绍如何使用启发式搜索—— AStar 算法来求解八数码问题。

问题描述

八数码问题的A星搜索算法实现

要求:设计估价函数,并采用c或python编程实现,以八数码为例演示A星算法的搜索过程,争取做到直观、清晰地演示算法,代码要适当加注释。

八数码难题:在3×3方格棋盘上,分别放置了标有数字1,2,3,4,5,6,7,8的八张牌,初始状态S0可自己随机设定,使用的操作有:空格上移,空格左移,空格右移,空格下移。试采用A*算法编一程序实现这一搜索过程。

算法描述

预估值的设计

A* 算法的花费为 f(n) = g(n) + h(n),其中 g(n) 为搜索深度,定义为状态单元 state 的成员变量,在每次生成子节点时将其加一。h(n) 为不对位的将牌数,将该部分的计算重载于 state 的小于运算符中,并将 f(n) = g(n) + h(n) 的值作为状态单元的比较值。

数据结构设计

  • 每个状态用一个结构体表示,其中 depth 为状态深度,str 为该状态字符串,并重载小于运算符用于计算最优。
  • open 表使用优先队列 priority_queue,实现在 O(logn) 的时间复杂度内获取最优值。
  • close 表使用哈希集合 unordered_set,实现在 O(1) 时间复杂度内判断某状态是否已位于 close 表中。
  • 而为了得到最优搜索路径,还需要将每个状态的前驱加以保存,前驱表 pre 我使用了哈希表 unordered_map,模板类型为 pair<string, string>,表示 key 的前驱为 value。

代码

#include<iostream>
#include<string>
#include<vector>
#include<queue>
#include<unordered_map>
#include<unordered_set>
#include<stack>
using namespace std;

class Solution {
private:
	static string targetStr;
	const vector<vector<int>> dirs = { {-1,0},{1,0},{0,-1},{0,1} }; // 四个移动方向
	struct state
	{
		string str;
		int depth;
		state(string s, int d) : str(s), depth(d) {}
		bool operator < (const state& s) const {
			int cnt1 = 0, cnt2 = 0;
			for (int i = 0; i < 9; ++i) {
				if (s.str[i] != targetStr[i])
					++cnt1;
				if (this->str[i] != targetStr[i])
					++cnt2;
			}
			return cnt1 + this->depth > cnt2 + s.depth; // f(n) = g(n) + h(n)			
		}
	};
	inline void swapChr(string& child, int iniInd, int childInd) { // 交换字符,完成移动
		child[iniInd] = child[childInd];
		child[childInd] = '0';
	}
	void printPath(unordered_map<string, string>& pre, string path) { // 输出路径
		stack<string> st;
		while (path != "None") {
			st.emplace(path);
			path = pre[path];
		}
		int cnt = 0;
		while (++cnt && !st.empty()) {
			string str = st.top();
			st.pop();
			cout << "step" << cnt << ":  " << str.substr(0, 3) << endl
				<< "        " << str.substr(3, 3) << endl << "        " <<
				str.substr(6, 3) << endl << string(15, '-') << endl;
		}
	}
public:
	void eightDigitalQues(const string& ini, const string& target) {
		targetStr = target;
		priority_queue<state> open;
		unordered_set<string> close;
		unordered_map<string, string> pre;
		open.emplace(ini, 0);
		pre[ini] = "None";
		while (!open.empty()) {
			string n = open.top().str;
			int d = open.top().depth;
			open.pop();
			close.emplace(n);
			if (n == target) {
				break;
			}
			int iniInd = n.find('0');
			int x = iniInd / 3, y = iniInd % 3;
			for (const auto& dir : dirs) { // 尝试选择四个方向
				int nx = x + dir[0], ny = y + dir[1];
				if (nx >= 0 && nx <= 2 && ny >= 0 && ny <= 2) { // 满足移动后下标满足条件
					int childInd = nx * 3 + ny;
					state childState(n, d + 1);
					swapChr(childState.str, iniInd, childInd);
					if (close.count(childState.str)) // 如该状态已加入close表,则跳过
						continue;
					open.emplace(childState); // 加入满足条件的子状态
					pre[childState.str] = n; // 更新前驱
				}
			}
		}
		printPath(pre, target); // 输出流程
		return;
	}
};
string Solution::targetStr;
int main() {
	Solution S;
	string ini, target;
	cin >> ini >> target;
	S.eightDigitalQues(ini, target);
	cin.get();
}

运行结果

输入

原状态:283164705, 目标状态:123804765

输出

在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A*算法求解八数码问题 1、A*算法基本思想: 1)建立一个队列,计算初始结点的估价函数f,并将初始结点入队,设置队列头和尾指针。 2)取出队列头(队列头指针所指)的结点,如果该结点是目标结点,则输出路径,程序结束。否则对结点进行扩展。 3)检查扩展出的新结点是否与队列中的结点重复,若与不能再扩展的结点重复(位于队列头指针之前),则将它抛弃;若新结点与待扩展的结点重复(位于队列头指针之后),则比较两个结点的估价函数中g的大小,保留较小g值的结点。跳至第五步。 4)如果扩展出的新结点与队列中的结点不重复,则按照它的估价函数f大小将它插入队列中的头结点后待扩展结点的适当位置,使它们按从小到大的顺序排列,最后更新队列尾指针。 5)如果队列头的结点还可以扩展,直接返回第二步。否则将队列头指针指向下一结点,再返回第二步。 2、程序运行基本环境: 源程序所使用编程语言:C# 编译环境:VS2010,.net framework 4.0 运行环境:.net framework 4.0 3、程序运行界面 可使用程序中的test来随机生成源状态与目标状态 此停顿过程中按Enter即可使程序开始运行W(n)部分; 此停顿部分按Enter后程序退出; 4、无解问题运行情况 这里源程序中是先计算源状态与目标状态的逆序对的奇偶性是否一致来判断是否有解的。下面是无解时的运行画面: 输入无解的一组源状态到目标状态,例如: 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 8 7 0 运行画面如下: 5、性能比较 对于任一给定可解初始状态,状态空间有9!/2=181440个状态;当采用不在位棋子数作为启发函数时,深度超过20时,算法求解速度较慢; 其中启发函数P(n)与W(n)的含义如下: P(n): 任意节点与目标结点之间的距离; W(n): 不在位的将牌数; 源状态 目标状态 P(n) 生成节点数 W(n) 生成节点数 P(n) 扩展节点数 W(n) 扩展节点数 2 8 3 1 6 4 7 0 5 1 2 3 8 0 4 7 6 5 11 13 5 6 1 2 3 8 0 4 7 6 5 0 1 3 8 2 4 7 6 5 6 6 2 2 4 8 2 5 1 6 7 0 3 7 4 2 8 5 6 1 3 0 41 79 22 46 6 2 5 8 7 0 3 1 4 0 3 6 7 1 8 4 5 2 359 10530 220 6769 7 6 3 1 0 4 8 5 2 2 8 7 1 3 4 6 5 0 486 8138 312 5295 下图是解决随机生成的100中状态中,P(n)生成函数的生成节点与扩展节点统计图: 由上图可知,P(n)作为启发函数,平均生成节点数大约在1000左右,平均扩展节点数大约在600左右; 下图是解决随机生成的100中状态中,W(n)生成函数的生成节点与扩展节点统计图: 由上图可知,W (n)作为启发函数,平均生成节点数大约在15000左右,是P(n)作为启发函数时的平均生成节点的15倍;W (n)作为启发函数,平均扩展节点数大约在10000左右,是P(n)作为启发函数时的平均扩展节点的15倍; 下图是解决随机生成的100中状态中,两个生成函数的生成节点与扩展节点统计图: 由上述图表可以看到,将P(n)作为启发函数比将W(n)作为启发函数时,生成节点数与扩展节点数更稳定,相比较来说,采用P(n)作为启发函数的性能比采用W(n)作为启发函数的性能好。 6、源代码说明 1)AStar-EightDigital-Statistics文件夹:用来随机生成100个状态,并对这100个状态分别用P(n)与W(n)分别作为启发函数算出生成节点以及扩展节点,以供生成图表使用;运行界面如下: 2)Test文件夹:将0-8这9个数字随机排序,用来随机生成源状态以及目标状态的;运行界面如下: 3)AStar-EightDigital文件夹:输入源状态和目标状态,程序搜索出P(n)与W(n)分别作为启发函数时的生成节点数以及扩展节点数,并给出从源状态到目标状态的移动步骤;运行界面如下: 提高了运行速度的几处编码思想: 1、 在维护open以及close列表的同时,也维护一个类型为hashtable的open以及close列表,主要用来提高判断当前节点是否在open列表以及close列表中出现时的性能; 2、 对于每个状态,按照从左到右,从上到下,依次将数字拼接起来,形成一个唯一标识identify,通过该标识,可以直接判断两个状态是否是同一个状态,而不需要循环判断每个位置上的数字是否相等 3、 在生成每个状态的唯一标识identify时,同时计算了该状态的空格所在位置,通过空格所在位置,可以直接判断能否进行上移、下移、左移、右移等动作; 4、 只计算初始节点的h值,其它生成的节点的h值是根据当前状态的h值、移动的操作等计算后得出的,规则如下: a) 采用W(n)这种方式,不在位置的将牌数,共有以下3中情况: i. 该数字原不在最终位置上,移动后,在其最终位置上 这种情况下,生成的子节点的h值= 父节点的h值-1 ii. 该数字原在最终位置上,移动后,不在其最终位置上 这种情况下,生成的子节点的h值= 父节点的h值 +1 iii. 该数字原不在最终位置上,移动后,还是不在其最终位置上 这种情况下,生成的子节点的h值= 父节点的h值 iv. 该数字原在最终位置上,移动后,还在其最终位置 这种情况不存在 b) 采用P(n)这种方式,节点与目标距离,可通过下面3步完成 i. 首先计算在原位置时,与目标位置的距离,命名为Distance1 ii. 移动后,计算当前位置与目标位置的距离,命名为Distance2 iii. 计算子节点的h值: 子节点的h值 = 父节点的h值- Distance1+ Distance2 5、 在任意状态中的每个数字和目标状态中同一数字的相对距离就有9*9种,可以先将这些相对距离算出来,用一个矩阵存储,这样只要知道两个状态中同一个数字的位置,就可查出它们的相对距离,也就是该数字的偏移距离;例如在一个状态中,数字8的位置是3,在另一状态中位置是7,那么从矩阵的3行7列可找到2,它就是8在两个状态中的偏移距离。
好的,以下是使用A*算法解决八数码问题的Python代码: ```python import heapq # 定义节点类 class Node: def __init__(self, state, parent=None, action=None, cost=0): self.state = state self.parent = parent self.action = action self.cost = cost self.heuristic = self.get_heuristic() # 定义估价函数 def get_heuristic(self): # 曼哈顿距离 h = 0 for i in range(1, 9): x1, y1 = self.state.index(str(i)) // 3, self.state.index(str(i)) % 3 x2, y2 = (i - 1) // 3, (i - 1) % 3 h += abs(x1 - x2) + abs(y1 - y2) return h # 定义比较函数 def __lt__(self, other): return (self.cost + self.heuristic) < (other.cost + other.heuristic) # 定义A*算法函数 def astar(start, goal): # 定义open和closed表 open_list = [] closed_list = set() # 将起始节点加入open表 start_node = Node(start) heapq.heappush(open_list, start_node) # 循环直到open表为空 while open_list: # 取出open表中f值最小的节点 current_node = heapq.heappop(open_list) # 如果当前节点是目标节点,则返回解路径 if current_node.state == goal: path = [] while current_node.parent: path.append(current_node.action) current_node = current_node.parent return path[::-1] # 将当前节点加入closed表 closed_list.add(current_node.state) # 扩展当前节点 x = current_node.state.index("0") // 3 y = current_node.state.index("0") % 3 actions = [] if x > 0: actions.append("u") if x < 2: actions.append("d") if y > 0: actions.append("l") if y < 2: actions.append("r") for action in actions: if action == "u": new_state = current_node.state[:3*(x-1)] + current_node.state[3*x:3*(x+1)] + current_node.state[3*(x-1):3*x] + current_node.state[3*(x+1):] elif action == "d": new_state = current_node.state[:3*x] + current_node.state[3*(x+1):3*(x+2)] + current_node.state[3*x:3*(x+1)] + current_node.state[3*(x+2):] elif action == "l": new_state = current_node.state[:3*x+y-1] + current_node.state[3*x+y] + current_node.state[3*x+y-1] + current_node.state[3*x+y+1:] else: new_state = current_node.state[:3*x+y] + current_node.state[3*x+y+1] + current_node.state[3*x+y+2] + current_node.state[3*x+y+3:] if new_state not in closed_list: new_node = Node(new_state, current_node, action, current_node.cost+1) heapq.heappush(open_list, new_node) # 如果open表为空,表示无解 return None # 测试 start = "283164705" goal = "123804765" path = astar(start, goal) print(path) ``` 以上就是使用A*算法解决八数码问题的Python代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值