Code:
#include <bits/stdc++.h>
using namespace std;
#define MAIN signed main()
const int maxn = 1e5+5;
int d, des;
char num[10];
int op[3];
int A(int x) //A操作
{
sprintf(num,"%d",x); //使用后sprintf函数 将 x 转换为数组
swap(num[0],num[7]);swap(num[1],num[6]);swap(num[2],num[5]);swap(num[3],num[4]);
sscanf(num,"%d",&x);//使用sscanf将num 转换为整数
return x;
}
int B(int x)//B操作
{
sprintf(num,"%d",x);
char upR = num[3];
char downR = num[4];
num[3] = num[2];num[2] = num[1];
num[1] = num[0];num[4] = num[5];num[5] = num[6];num[6] = num[7];num[0] = upR;num[7] = downR;
sscanf(num,"%d",&x);
return x;
}
int C(int x)//C操作
{
sprintf(num,"%d",x);
char tmp = num[1];num[1] = num[6];num[6] = num[5];num[5] = num[2];num[2] = tmp;
sscanf(num,"%d",&x);
return x;
}
map<int,pair<int,char>> pre; //前一个状态 以及如何转移
map<int,int> dist;
queue<int> Q;
vector<char> res;
int bfs()
{
Q.push(12345678); //初始状态
dist[12345678] = 0;
while(!Q.empty())
{
int f = Q.front();Q.pop();
if(f == des) //到达目标状态
{
cout << dist[f] << endl;
while(pre.count(f))
{
res.push_back(pre[f].second);
f = pre[f].first;
}
for(int i=res.size()-1;i>=0;--i)
printf("%c",res[i]);
break;
}
op[0] = A(f), op[1] = B(f), op[2] = C(f);
for(int i=0;i<3;++i)
{
if(dist.count(op[i]) == 0)
{
dist[op[i]] = dist[f] + 1;
Q.push(op[i]);
pre[op[i]] = {f,'A'+i};
}
}
}
}
MAIN
{
for(int i=1;i<=8;++i)
{
scanf("%d",&d);
des = des * 10 + d;
} //将输入转换为一个整数
bfs();
return 0;
}