标准的BFS吧,三种方式A B C共性挺多,所以挺好写的
看代码吧
/*
ID:xsy97051
LANG:C++
TASK:msquare
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
short r[3][5],a[3][5]; //目标 初始
bool vis[9][9][9][9][9][9][9]; // 4MB 判重
struct node //每种状态
{
int dep;
string str;
short b[3][5];
} q[50000];
void A(short b[5][5])
{
for(int i=1;i<=4;i++)
swap(b[1][i],b[2][i]);
}
void B(short b[5][5])
{
b[1][0]=b[1][4];
b[2][0]=b[2][4];
for(int i=4;i>=1;i--)
{
b[1][i]=b[1][i-1];
b[2][i]=b[2][i-1];
}
}
void C(short b[5][5])
{
int tmp;
tmp=b[1][3];
b[1][3]=b[1][2];
b[1][2]=b[2][2];
b[2][2]=b[2][3];
b[2][3]=tmp;
}
bool pan(short r[5][5],short b[5][5])
{
for(int i=1;i<=2;i++)
for(int j=1;j<=4;j++)
if(r[i][j]!=b[i][j])
return 0;
return 1;
}
void BFS()
{
memset(vis,0,sizeof(vis));
memcpy(q[0].b,a,sizeof(a));
q[0].dep=0; q[0].str="";
vis[q[0].b[1][1]][q[0].b[1][2]][q[0].b[1][3]][q[0].b[1][4]][q[0].b[2][1]][q[0].b[2][2]][q[0].b[2][3]]=1;
int head=0,tail=1;
node next,p;
while(1)
{
p=q[head];
head++;
head%=50000;
if(pan(r,p.b))
{
cout<<p.dep<<endl<<p.str<<endl;
break;
}
//A
next=p;
next.dep=p.dep+1;
next.str=p.str+"A";
A(next.b);
if(!vis[next.b[1][1]][next.b[1][2]][next.b[1][3]][next.b[1][4]][next.b[2][1]][next.b[2][2]][next.b[2][3]])
{
q[tail]=next;
tail++;
tail%=50000;
vis[next.b[1][1]][next.b[1][2]][next.b[1][3]][next.b[1][4]][next.b[2][1]][next.b[2][2]][next.b[2][3]]=1;
}
//B
next=p;
next.dep=p.dep+1;
next.str=p.str+"B";
B(next.b);
if(!vis[next.b[1][1]][next.b[1][2]][next.b[1][3]][next.b[1][4]][next.b[2][1]][next.b[2][2]][next.b[2][3]])
{
q[tail]=next;
tail++;
tail%=50000;
vis[next.b[1][1]][next.b[1][2]][next.b[1][3]][next.b[1][4]][next.b[2][1]][next.b[2][2]][next.b[2][3]]=1;
}
//C
next=p;
next.dep=p.dep+1;
next.str=p.str+"C";
C(next.b);
if(!vis[next.b[1][1]][next.b[1][2]][next.b[1][3]][next.b[1][4]][next.b[2][1]][next.b[2][2]][next.b[2][3]])
{
q[tail]=next;
tail++;
tail%=50000;
vis[next.b[1][1]][next.b[1][2]][next.b[1][3]][next.b[1][4]][next.b[2][1]][next.b[2][2]][next.b[2][3]]=1;
}
}
}
int main()
{
freopen("msquare.in","r",stdin);
freopen("msquare.out","w",stdout);
for(int j=1;j<=4;j++)
cin>>r[1][j];
for(int i=4;i>=1;i--)
cin>>r[2][i];
for(int i=1;i<=4;i++)
{
a[1][i]=i;
a[2][i]=8-i+1;
}
BFS();
return 0;
}