#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 1e5+10;
string startt;
string endd = "12345678x";
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
/*
将3*3网格用string存储
*/
int bfs() {
// 用于BFS的一个队列
queue<string> q;
// 每一个string对应的distance的哈希map
unordered_map<string, int> d;
// 用来记录distance的数组 每次搜索并记录
d[startt] = 0;
q.push(startt);
while(q.size()) {
// 当前字符序列
string t = q.front();
q.pop();
int distance = d[t];
if(t == endd) {
return distance;
}
// 将x在string中的位置转换到网格中 x y分别是横纵坐标
int k = t.find('x');
int x = k / 3, y = k % 3;
// 对网格进行一层BFS
for(int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < 3 && b >= 0 && b < 3) {
// 用t暂存变换完的字符串
swap(t[k], t[a*3 + b]);
// 如果没有过则入队
if(!d.count(t)) {
q.push(t);
d[t] = distance + 1;
}
// 恢复t
swap(t[k], t[a*3 + b]);
}
}
}
return -1;
}
int main() {
for(int i = 0; i < 9; i++) {
char c;
cin >> c;
startt += c;
}
cout << bfs() << endl;
return 0;
}
AcW 845 八数码 【BFS、queue、unordered_map】
最新推荐文章于 2023-10-27 14:27:41 发布