//本代码还未ac
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define between(x, a, b) (a<=x && x<=b)
const int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
const int N = 1e6 + 10;
int n, m, K;
int f[15], vis[N];
struct node {
string s="";
int pos;//x的位置
int step;
};
int id(string s) { //一种哈希方式 变排列
int res = 0;
for (int i = 0; i < 9; ++i) {
int d = 0;
for (int j = 0; j < i; ++j) {
if (s[j] > s[i]) d++;
}
res += d * f[i];
}
return res;
}
int dfs(node st) {
vis[id(st.s)] = 1;
queue<node> q;
q.push(st);
while (!q.empty()) {
auto u = q.front();
q.pop();
if (u.s == "123456789x") return u.step;
if(vis[id(u.s)])continue;
vis[id(u.s)]=1;
int x = u.pos / 3;
int y = u.pos % 3;
for (int i = 0; i < 4; ++i) {
int dx = x + dir[i][0];
int dy = y + dir[i][1];
if (between(dx, 0, 2) && between(dy, 0, 2)) {
int now = dx * 3 + dy;
swap(u.s[u.pos], u.s[now]);
if (vis[id(u.s)]) continue;
node v = {u.s, now, u.step + 1};
q.push(v);
swap(u.s[u.pos], u.s[now]);
}
}
}
return -1;
}
int main() {
ios::sync_with_stdio(0);
f[0] = 1; //预处理 n!
for (int i = 1; i <= 9; ++i) {
f[i] = f[i - 1] * i;
}
string s;
node start;
for (int i = 0; i < 9; ++i) {
cin >> s;
if (s == "x") start.pos = i;
start.s += s;
}
cout << dfs(start) << endl;
return 0;
}
来源:CSDN
作者:Zaller
链接:https://blog.csdn.net/Yubing792289314/article/details/104722241