题目
思路
用bfs,分别模拟每一步的转动情况
代码
#include<iostream>
#include<queue>
#include<map>
using namespace std;
map<string,bool> ma;//标记
struct node{
string statu;
int step;
}first,last;
queue<node> q;
string next_dir(int i,string s){
char temp;
if(i==1){//第一行左转
temp=s[0];
s[0]=s[1];
s[1]=s[2];
s[2]=temp;
}else if(i==2){//第二行左转
temp=s[3];
s[3]=s[4];
s[4]=s[5];
s[5]=temp;
}else if(i==3){//第三行左转
temp=s[6];
s[6]=s[7];
s[7]=s[8];
s[8]=temp;
}else if(i==4){//第一行往右
temp=s[2];
s[2]=s[1];
s[1]=s[0];
s[0]=temp;
}else if(i==5){//第二行往右
temp=s[5];
s[5]=s[4];
s[4]=s[3];
s[3]=temp;
}else if(i==6){//第三行往右
temp=s[8];
s[8]=s[7];
s[7]=s[6];
s[6]=temp;
}else if(i==7){//第一列往上
temp=s[0];
s[0]=s[3];
s[3]=s[6];
s[6]=temp;
}else if(i==8){//第二列往上
temp=s[1];
s[1]=s[4];
s[4]=s[7];
s[7]=temp;
}else if(i==9){//第三列往上
temp=s[2];
s[2]=s[5];
s[5]=s[8];
s[8]=temp;
}else if(i==10){//第一列往下
temp=s[6];
s[6]=s[3];
s[3]=s[0];
s[0]=temp;
}else if(i==11){//第二列往下
temp=s[7];
s[7]=s[4];
s[4]=s[1];
s[1]=temp;
}else{ //第三列往下
temp=s[8];
s[8]=s[5];
s[5]=s[2];
s[2]=temp;
}
return s;
}
int main(){
string t1,t2,t3;
cin>>t1>>t2>>t3;
first.statu=t1+t2+t3;
last.statu="123456789";
ma[first.statu]=true;
q.push(first);
node a,next;
while(!q.empty()){
a=q.front();
q.pop();
if(a.statu==last.statu){//出口
cout<<a.step<<endl;
break;
}
for(int i=1;i<=12;i++){
string tem=next_dir(i,a.statu);
if(!ma[tem]){
ma[tem]=true;
next.statu=tem;
next.step=a.step+1;
q.push(next);
}
}
}
if(a.statu!=last.statu){
cout<<"-1"<<endl;
}
return 0 ;
}