//将二维坐标映射成一维点(下标从0开始) n是二维数组边长(正方形)intget(int x,int y){
return x * n + y;}//一维坐标转化未二维坐标,k表示一维下标,n表示转化为二维坐标的边长int x = k / n , y = k % n ;
代码
#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<algorithm>#include<unordered_map>#include<queue>usingnamespace std;constint N =1e5+10;int dx[4]={
-1,0,1,0};int dy[4]={
0,1,0,-1};intbfs(string start){
string end ="12345678x";
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('x');//将一维坐标转化成二维坐标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;}intmain(){
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;return0;}