原题链接:
题解:
bfs求解:实质就是将每个二维数组的状态都用字符串存储,然后使用unordered_map记录每个状态对应的移动次数,然后不断进行上下左右4种操作(如果该种状态之前没有出现过,就加入到队列中去),不断循环,直到队列为空(此时已经遍历过所有状态了),如果还是没有还原,则输出-1>
详细思路可以参考:AcWing 845. 八数码 - AcWing
代码:
#include<bits/stdc++.h>
using namespace std;
int bfs(string s) {
unordered_map<string, int> d;//存储字符串(状态)对应的交换次数
//使用unordered_map的好处是查找复杂度为O(1),而map需要二分,为O(log n)
queue<string> q;//存储当前状态
q.push(s);
d[s] = 0;
string end = "12345678x";//结束状态
int dx[] = { 0, 0, -1, 1 }, dy[] = { 1,-1,0,0 };//四种位移
while (q.size()) {
string F = q.front();
int dis = d[F];
q.pop();
if (F == end) return dis;
int pos = F.find('x');//找出x在原本字符串中的位置pos
int x = pos % 3, y = pos / 3;
for (int i = 0;i < 4;i++) {
int x1 = x + dx[i], y1 = y + dy[i];//移动后的坐标
if (x1 >= 0 && x1 < 3 && y1 >= 0 && y1 < 3) {
swap(F[pos], F[x1 + y1 * 3]);//先交换
if (!d.count(F)) {
d[F] = dis + 1;
q.push(F);
}
swap(F[pos], F[x1 + y1 * 3]);还原状态,为下一种转换情况做准备
}
}
}
return -1;
}
int main() {
string tmp, start="";
for (int i = 0;i < 9;i++) {
cin >> tmp;
start += tmp;
}
cout << bfs(start);
}