想了好久,终于出来了
先贴个代码,回来再写
#include <iostream>
#include<queue>
#include<cstdio>
#define N 9
using namespace std;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int vis[400000]= {0}, fact[9];
struct node
{
int eight[N];
int num;
int dist=0;
}intial,last,temp;
queue<node> Q;
void prin(node *p)
{
for(int i=0; i<N; i++)
printf("%d ",p->eight[i]);
printf("\n");
}
void fac()
{
fact[0] = 1;
for(int i = 1; i < N; i++) fact[i] = fact[i-1] * i;
}
void change(node &t)
{
t.num=0;
for(int i = 0; i < 9; i++)
{
int cnt = 0;
for(int j = i+1; j < 9; j++)
if(t.eight[j] < t.eight[i])
cnt++;
// printf("change %d %d %d ",t.num,fact[8-i],cnt);
t.num += fact[8-i] * cnt;
// printf(" %d\n",t.num);
}
// printf("\n");
}
int bfs()
{
while(!Q.empty())
Q.pop();
if(intial.num==last.num)
return 0;
Q.push(intial);
while(!Q.empty())
{
int z;
for(z = 0; z < N; z++)
if(!Q.front().eight[z])
break;
int x = z/3, y = z%3;
//printf("\n");
// prin(&Q.front());
// printf("front : %d %d %d\n\n",Q.front().num,Q.front().dist,vis[Q.front().num]);
for(int d = 0; d < 4; d++)
{
temp=Q.front();
int newx = x + dx[d];
int newy = y + dy[d];
int newz = newx * 3 + newy;
// prin(&temp);
// printf(" poi : %d %d %d %d\n",newx,newy,newz,vis[temp.num]);
if(newx >= 0 && newx < 3 && newy >= 0 && newy < 3)
{
temp.eight[z]=Q.front().eight[newz];
temp.eight[newz]=Q.front().eight[z];
temp.dist=Q.front().dist+1;
change(temp);
if(!vis[temp.num])
{
// prin(&temp);
// printf("temp : %d %d %d\n",temp.num,temp.dist,vis[temp.num]);
if(temp.num==last.num)
return temp.dist;
vis[temp.num]=1;
Q.push(temp);
}
}
}
Q.pop();
}
}
int main()
{
freopen("input.txt","r",stdin);
int i;
fac();
for(i=0; i<N; i++)
intial.eight[i]=N-i;
for(i=0; i<N; i++)
scanf("%d",&intial.eight[i]);
for(i=0; i<N; i++)
scanf("%d",&last.eight[i]);
change(intial);
change(last);
//bfs();
// prin(&intial);
// prin(&last);
// printf("last : %d %d %d\n",last.num,last.dist,vis[last.num]);
// printf("intial : %d %d %d\n",intial.num,intial.dist,vis[intial.num]);
printf("%d\n",bfs());
return 0;
}