Acwing_845(八数码)

原题链接:

845. 八数码 - AcWing题库

题解:

bfs求解:实质就是将每个二维数组的状态都用字符串存储,然后使用unordered_map记录每个状态对应的移动次数,然后不断进行上下左右4种操作(如果该种状态之前没有出现过,就加入到队列中去),不断循环,直到队列为空(此时已经遍历过所有状态了),如果还是没有还原,则输出-1>

详细思路可以参考:AcWing 845. 八数码 - AcWing

代码:

#include<bits/stdc++.h>
using namespace std;

int bfs(string s) {
	unordered_map<string, int> d;//存储字符串(状态)对应的交换次数
	//使用unordered_map的好处是查找复杂度为O(1),而map需要二分,为O(log n)
	queue<string> q;//存储当前状态
	q.push(s);
	d[s] = 0;
	string end = "12345678x";//结束状态
	int dx[] = { 0, 0, -1, 1 }, dy[] = { 1,-1,0,0 };//四种位移
	while (q.size()) {
		string F = q.front();
		int dis = d[F];
		q.pop();
		if (F == end) return dis;

		int pos = F.find('x');//找出x在原本字符串中的位置pos
		int x = pos % 3, y = pos / 3;

		for (int i = 0;i < 4;i++) {
			int x1 = x + dx[i], y1 = y + dy[i];//移动后的坐标
			if (x1 >= 0 && x1 < 3 && y1 >= 0 && y1 < 3) {
				swap(F[pos], F[x1 + y1 * 3]);//先交换
				if (!d.count(F)) {
					d[F] = dis + 1;
					q.push(F);
				}
				swap(F[pos], F[x1 + y1 * 3]);还原状态,为下一种转换情况做准备
			}
		}
	}
	return -1;
}

int main() {
	string tmp, start="";
	for (int i = 0;i < 9;i++) {
		cin >> tmp;
		start += tmp;
	}
	cout << bfs(start);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值