P1379 八数码难题

知识点:广搜

难度:5

这个题和挑战程序设计竞赛后面的题简直是一模一样,甚至还简单了一点,只用了广搜就过了这个题,但是时间跑的相对慢一点,看题解发现很多双向广搜,A*等等高级的算法,等学到了再写把,

这个题的状态也是一整个矩阵,状态的表示方法和又当前状态遍历相邻的状态我也是用的同样的方法,当前一维->当前二维->相邻二维->相邻一维,个人感觉这个方法还是不错的

#include <bits/stdc++.h>

using namespace std;

int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
string s;
unordered_map<string, int> mp;

int bfs() {
	queue<string> q;
	q.push(s);
	mp[s] = 0;
	while (!q.empty()) {
		string now = q.front(); q.pop();
		if (now == "123804765") return mp[now];
		int pos = now.find('0');
		int x = pos / 3;
		int y = pos % 3;
		for (int i = 0; i < 4; i++) {
			int x1 = x + dx[i];
			int y1 = y + dy[i];
			if (x1 < 0 || x1 > 2 || y1 < 0 || y1 > 2) continue;
			int pos1 = x1 * 3 + y1;
			string s1 = now;
			swap(s1[pos], s1[pos1]);
			if (mp.find(s1) != mp.end()) continue;
			q.push(s1);
			mp[s1] = mp[now] + 1;
		}
	}
}

int main() {
	cin >> s;
	cout << bfs();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值