首先把每一种转换所对应的数组元素的一维下标找出来,然后对于每一种变换,找出对应的恢复方法,然后开始进行搜索,直到找到某种满足要求的状态为止,注意在查找变换的时候记得保存相应的变换的方法字母,最后输出就行了。具体实现如下:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;
int step;
char path[100];
int fLength;
int Move[8][7] = {
{0,2,6,11,15,20,22},
{1,3,8,12,17,21,23},
{10,9,8,7,6,5,4},
{19,18,17,16,15,14,13},
{23,21,17,12,8,3,1},
{22,20,15,11,6,2,0},
{13,14,15,16,17,18,19},
{4,5,6,7,8,9,10}
};
int Restore[] = {5,4,7,6,1,0,3,2};
int position[24];
bool check(){
if (position[11] != position[12]) return false;
int aim = position[11];
for (int i = 0; i < 3; i++){
if (position[6 + i] != aim || position[15 + i] != aim) return false;
}
return true;
}
void change(int i){
int first = position[Move[i][0]];
for (int j = 1; j < 7; j++){
position[Move[i][j - 1]] = position[Move[i][j]];
}
position[Move[i][6]] = first;
}
bool Solve(int k,int index,int last){
if (check()){
fLength = index;
return true;
}
int amount[4];
amount[1] = amount[2] = amount[3] = 0;
for (int i = 0; i < 3; i++){
amount[position[6 + i]]++;
amount[position[15 + i]]++;
}
amount[position[11]]++;
amount[position[12]]++;
amount[0] = max(max(amount[1], amount[2]), amount[3]);
if (8 + k - amount[0]>=step) return false;
for (int i = 0; i < 8; i++){
if (last!=-1&&Restore[i] == last) continue;
char dir = 'A' + i;
path[index] = dir;
change(i);
if(Solve(k+1,index+1,i))
return true;
change(Restore[i]);
}
return false;
}
int main(){
while (cin >> position[0] && position[0]){
for (int i = 1; i < 24; i++) cin >> position[i];
step = 1;
while (!Solve(0,0,-1)){
step++;
}
if (fLength == 0){
cout << "No moves needed" << endl << position[6] << endl;
continue;
}
for (int i = 0; i < fLength; i++) cout << path[i];
cout << endl<<position[6]<<endl;
}
return 0;
}