题目:

代码:
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
using namespace std;
int bfs(string state)
{
string end = "12345678x"; //定义终点:将3 X 3的数组展成一行,用字符串来表示其状态并存到队列中
queue<string> q; //记录每一个状态的距离
unordered_map<string, int> d; //定义距离数组
q.push(state); //state放入队列
d[state] = 0; //起点到起点的距离为0
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};//四个方向用向量表示:左(-1,0)右(0,1)上(1,0)下(0,-1);所以横坐标(-1,0,1,0),纵坐标(0,1,0,-1)
//宽搜过程
while (q.size())
{
auto t = q.front();
q.pop();
if (t == end) return d[t]; //t为终点就结束
//状态转移(1.字符串恢复成二维矩阵;2.转移:把x的四个位置分别枚举;3.移动后的二维矩阵恢复成字符串)
int distance = d[t];
int k = t.find('x'); //t存储x的下标
int x = k / 3, y = k % 3; //把一维数组的下标转化为二维数组的下标
for (int i = 0; i < 4; i ++ ) //枚举x的四个位置
{
int a = x + dx[i], b = y + dy[i]; //a,b表示移动后的下标
if (a >= 0 && a < 3 && b >= 0 && b < 3) //a,b没有出界
{
swap(t[a * 3 + b], t[k]); //交换x和(a,b):二维下标(a,b)对应到一维里(a*3+b)
if (!d.count(t)) //状态更新后当前t没有被搜到,即找到一个新的状态
{
d[t] = distance + 1; //新的状态的距离更新一下
q.push(t);
}
swap(t[a * 3 + b], t[k]); //恢复状态
}
}
}
return -1;
}
int main()
{
string state; //存初始状态
for (int i = 0; i < 9; i ++ )
{
char c;
cin >> c;
state += c;
}
cout << bfs(state) << endl;
return 0;
}