解题思路:题目给了我们2个字符串,因为是求最小值所以我们首先想到的应该是用BFS来做这道题(我这个憨憨一开始竟然是用DFS做的,我是真服了自己了),首先我们先要把题目给我们的起始字符串转化成二维数组,连带着把空格的坐标,当前的要走的步数弄成一个结构体,放到队列里面去宽搜,宽搜的时候注意把当前的状态再次转换成字符串标记一下状态,如果走到了终点就更新一下答案,如果当前状态没有走过就标记一下,放到队列里面,还要注意状态的转移,应该是把当前位置上的数变成搜到的位置上的数,搜到的位置上填'.'(空格),最后输出答案就好了。
上代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
string str1,str2;
char st[10][10],en[10][10];
int sx,sy,ex,ey;
int dx[]={-1,1,0,0},dy[]={0,0,-1,1};
struct node {
char sz[10][10];
int step,x,y;
};
map<string,int>mp;
int main()
{
cin>>str1>>str2;
node s;
for(int i=0;i<3;i++)
s.sz[1][i+1]=str1[i];
for(int i=3;i<6;i++)
s.sz[2][i-2]=str1[i];
for(int i=6;i<9;i++)
s.sz[3][i-5]=str1[i];
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
if(s.sz[i][j]=='.')
s.x=i,s.y=j;
queue<node>que;
int ans=0x3f3f3f3f;
que.push(s);
while(que.size())
{
auto t=que.front();
que.pop();
for(int i=0;i<4;i++)
{
node temp=t;
temp.x=t.x+dx[i];
temp.y=t.y+dy[i];
if(temp.x<1||temp.x>3||temp.y<1||temp.y>3)
continue;
temp.step=t.step+1;
temp.sz[t.x][t.y]=temp.sz[temp.x][temp.y];
temp.sz[temp.x][temp.y]='.';
string str="";
for(int j=1;j<=3;j++)
for(int k=1;k<=3;k++)
str+=temp.sz[j][k];
if(str==str2)
{
ans=min(ans,temp.step);
continue;
}
if(!mp[str])
{
mp[str]=1;
que.push(temp);
}
}
}
if(ans==0x3f3f3f3f)
cout<<"-1"<<endl;
else
cout<<ans<<endl;
return 0;
}