#include<bits/stdc++.h>
using namespace std;
string s;
queue<string> q;
unordered_map<string,int> d;//记录到达当前状态需要移动的步数
int bfs()
{
string end = "12345678x";//结束时的状态
q.push(s);//把字符串s放入队列
d[s] = 0;//记录到达当前状态的步数,因为是初始状态,步数为0
int dx[4] = {-1,0,+1,0},dy[4] = {0,+1,0,-1};
while(q.size())
{
string a = q.front();//取出队头
q.pop();//删除队头
int distance = d[a];
if(a == end) return distance;
int position = a.find('x');//找到字符x在字符串中的位置
int x1 = position / 3,y1 = position % 3;//找到x在矩阵中的位置
for(int i = 0; i < 4; i ++)
{
//向四个方向移动
int x = x1 + dx[i],y = y1 + dy[i];
if(x >= 0 && x < 3 && y >= 0 && y < 3)
{
swap(a[position],a[x * 3 + y]);
if(!d.count(a))//该状态是第一次找到
{
d[a] = distance + 1;
q.push(a);//将转变为之后的字符串放入
}
swap(a[position],a[x * 3 + y]);//恢复现场
}
}
}
return -1;//找不到结果
}
int main()
{
for(int i = 0; i < 9; i ++)
{
char c;
cin >> c;
s += c;//得到初始状态字符串
}
cout << bfs() << endl;
}
845. 八数码
最新推荐文章于 2024-07-25 21:43:46 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)