题面
题解
BFS经典八数码问题 :抽象成图,每一个状态都是都与上一个点相连,且距离为1,最终状态就是终点,转化成了从开始点到最终点的距离最小,因为每个点之间的距离都是1,所以直接用BFS来做即可
代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<unordered_map>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int dx[4] = {
-1, 0, 1, 0};
int dy[4] = {
0, 1, 0, -1};
int bfs(string start) {
string end = "123804765";
unordered_map<string, int> d;
queue<string> q;
q.push(start);
d[start] = 0;
while (q.size()) {
auto t = q.front();
q.pop();
if (t == end) return d[t];
//找到空位的下标
int k = t.find('0');
//将一维坐标转化成二维坐标
int x = k / 3, y = k % 3;
int dist = d[t];
for (int i = 0; i < 4; i++) {
//遍历4个方向
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < 3 && b >= 0 && b < 3) {
//符合放入形成新的状态
swap(t[k], t[a * 3 + b]);
if (!d.count(t)) {
d[t] = dist + 1;
q.push(t);
}
swap(t[k], t[a * 3 + b]);
}
}
}
return -1;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
string start = "";
for (int i = 1; i <= 9; i++) {
char c;
cin >> c;
start += c;
}
cout << bfs(start) << endl;
return 0;
}