经典的八数码问题
至于康托展开,百度知道。。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
int jc[11] = {1,1,2,6,24,120,720,5040,40320,362880};
bool vis[444444];
string path[444444];
int aim;
int mx[4] = {0,0,1,-1};
int my[4] = {1,-1,0,0};
char direction[4] = {'l','r','u','d'};
struct State{
int x,y;
int s[11];
int state;
string path;
};
char mp[4][4];
bool in(State a){
if(a.x >= 0 && a.x < 3 && a.y >= 0 && a.y < 3)
return true;
else
return false;
}
int contor(int s[]){
int sum = 0;
for(int i = 0 ; i < 9 ; i ++){
int num = 0;
for(int j = i + 1 ; j < 9 ; j ++){
if(s[j] < s[i]){
num++;
}
}
sum += num*jc[9-i-1];
}
return sum + 1;
}
queue<State> q;
void BFS(){
memset(vis,0,sizeof(vis));
State s;
for(int i = 0 ; i < 8 ; i ++){
s.s[i] = i+1;
}
s.s[8] = 0;
s.state = contor(s.s);
s.x = 2;
s.y = 2;
s.path = "";
path[s.state] = "";
vis[s.state] = 1;
q.push(s);
while(!q.empty()){
State cnt = q.front();
q.pop();
for(int i = 0 ; i < 4 ; i ++){
State nt = cnt;
nt.x = cnt.x + mx[i];
nt.y = cnt.y + my[i];
if(in(nt) == 0)
continue;
nt.s[cnt.x*3+cnt.y] = nt.s[nt.x*3+nt.y];
nt.s[nt.x*3+nt.y] = 0;
nt.state = contor(nt.s);
if(vis[nt.state] == 0){
path[nt.state] = direction[i]+nt.path;
nt.path = path[nt.state];
vis[nt.state] = 1;
q.push(nt);
}
}
}
}
int main()
{
char str;
State now;
BFS();
while(cin>>str){
if(str == 'x'){
now.x = 0;
now.y = 0;
now.s[0] = 0;
}
else
now.s[0] = str - '0';
for(int i = 1 ; i < 9 ; i ++){
cin>>str;
if(str == 'x'){
now.x = i/3;
now.y = i%3;
now.s[i] = 0;
}
else
now.s[i] = str-'0';
}
now.state = contor(now.s);
if(vis[now.state] == 1)
cout<<path[now.state]<<endl;
else
cout<<"unsolvable"<<endl;
}
return 0;
}