描述
在一个3×3的网格中,1~8这8个数字和一个“x”恰好不重不漏地分布在这3×3的网格中。
例如:
1 2 3
x 4 6
7 5 8
在游戏过程中,可以把“x”与其上、下、左、右四个方向之一的数字交换(如果存在)。
我们的目的是通过交换,使得网格变为如下排列(称为正确排列):
1 2 3
4 5 6
7 8 x
例如,示例中图形就可以通过让“x”先后与右、下、右三个方向的数字交换成功得到正确排列。
输入占一行,将3×3的初始网格描绘出来。
例如,如果初始网格如下所示: 1 2 3
x 4 6
7 5 8
则输入为:1 2 3 x 4 6 7 5 8
输出占一行,包含一个整数,表示最少交换次数。
如果不存在解决方案,则输出”-1”。
#include<iostream>
#include<string>
#include<algorithm>
#include<unordered_map>
#include<queue>
using namespace std;
int bfs(string state)
{
queue<string> q;
unordered_map<string,int> d;
q.push(state);
d[state]=0;
int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
string end="12345678x";
while(q.size())
{
auto t=q.front();
q.pop();
if(t==end)return d[t];
int distance=d[t];
int k=t.find('x');
int x=k/3,y=k%3;
for(int i=0;i<4;i++)
{
int tx=x+dx[i],ty=y+dy[i];
if(tx>=0&&tx<3&&ty>=0&&ty<3)
{
swap(t[tx*3+ty],t[k]);
if(!d.count(t))
{//若t情况还未出现过
d[t]=distance+1;
q.push(t);
}
swap(t[tx*3+ty],t[k]);
}
}
}
return -1;
}
int main()
{
char s[2];
string state;
for(int i=0;i<9;i++)
{
cin>>s;
state+=*s;
}
cout<<bfs(state)<<endl;
return 0;
}