A*解决八数码问题,估计函数为当前状态所有不在目标状态上的数字的曼哈顿距离之和,如果变小则更新状态,变大则剪枝舍弃这个状态。
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i = a;i<n;i++)
#define per(i,a,n) for(int i = n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define yes cout<<"YES"<<'\n';
#define no cout<<"NO"<<'\n';
#define endl '\n';
#define R register
typedef vector<int> VI;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}());
const ll MOD=1000000007;
int rnd(int x) {return mrand() % x;}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;};
ll lcm(int a,int b){return a*b/gcd(a,b);};
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int f(string stu){
int res=0;
rep(i,0,SZ(stu)){
if(stu[i]!='x'){
int t=stu[i]-'1';
res+=abs(i/3-t/3)+abs(i%3-t%3);
}
}
return res;
}
string bfs(string st){
string end="12345678x";
char op[]={"urdl"};
unordered_map<string,int> dist;
unordered_map<string,pair<char,string>> pre;
priority_queue<pair<int,string>,vector<pair<int,string>>,greater<pair<int,string>>> q;
dist[st]=0;
q.push({f(st),st});
while(!q.empty()){
auto t=q.top();
q.pop();
string stu=t.se;
if(stu==end) break;
int x,y;
rep(i,0,9){
if(stu[i]=='x'){
x=i/3,y=i%3;
break;
}
}
string ori=stu;
rep(i,0,4){
int xx=x+dx[i],yy=y+dy[i];
if(xx<0||xx>=3||yy<0||yy>=3) continue;
stu=ori;
swap(stu[x*3+y],stu[xx*3+yy]);
if(dist[stu]==0||dist[stu]>dist[ori]+1){
dist[stu]=dist[ori]+1;
pre[stu]={op[i],ori};
q.push({dist[stu]+f(stu),stu});
}
}
}
string res;
while(end!=st){
res+=pre[end].fi;
end=pre[end].se;
}
reverse(all(res));
return res;
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
string stu,seq;
char c;
while(cin>>c){
stu+=c;
if(c!='x') seq+=c;
}
int cnt=0;
rep(i,0,8){
rep(j,i,8){
if(seq[i]>seq[j]) cnt++;
}
}
if(cnt&1) puts("unsolvable");
else cout<<bfs(stu)<<endl;
return 0;
}