点击打开链接
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<cstring>
#include<string>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
using namespace std;
struct Node{
int x,y;
int steps;
string s;
};
const int dx[]={-1,1,0,0};
const int dy[]={0,0,-1,1};
queue<Node>Q;
set<string>vis;
string s1,s2;
void BFS()
{
int i=0,z=0,x=0,y=0,newz=0;
while(!Q.empty()) Q.pop();
vis.clear();
for(z=0;z<9;z++) if(s1[z]=='.') break;
Node temp1,temp2;
temp1.x=z/3;temp1.y=z%3;temp1.steps=0;temp1.s=s1;
vis.insert(s1);
Q.push(temp1);
while(!Q.empty()){
temp1=Q.front();Q.pop();
/// cout<<temp1.s<<endl;
if(temp1.s.compare(s2)==0){///c++中的字符串比较。
printf("%d\n",temp1.steps);
return;
}
for(i=0;i<4;i++){
temp2=temp1;
z=temp1.x*3+temp1.y;
temp2.x+=dx[i];temp2.y+=dy[i];
newz=temp2.x*3+temp2.y;
if(temp2.x>=0&&temp2.x<3&&temp2.y>=0&&temp2.y<3&&newz>=0&&newz<9){
swap(temp2.s[z],temp2.s[newz]);
if(!vis.count(temp2.s)){
vis.insert(temp2.s);
temp2.steps+=1;
Q.push(temp2);
}
}
}
}
printf("-1\n");
}
int main()
{
cin>>s1>>s2;
BFS();
return 0;
}