参考http://blog.sina.com.cn/s/blog_b1e4dca501013z88.html思路,给出非9重循环的程序实现:
#include <iostream>
#include <stdio.h>
using namespace std;
// clock的位置
int A[9];
// 思路 :首先确定“局部” :前三个操作。
// 然后查看后续操作能否满足要求。
bool isClock(int* a){
for (int i=0;i<9;i++) {
if(a[i]!=0)
return false;
}
return true;
}
bool getNextCond(int * container)
{
int i = 0;
container[0]++;
while (container[i] >= 4)
{
container[i] = 0;
i++;
if (i >= 3)
return false;
container[i]++;
}
return true;
}
bool getCurOper(int* container,const int * src, int& tmp)
{
int tmpA = (src[0] + container[0] + container[1])%4;
int tmpB = (src[1] + container[0] + container[1] + container[2])%4;
int tmpC = (src[2] + container[1] + container[2])%4;
container[3] = (4-tmpA)%4;
container[4] = (4-tmpB)%4;
container[5] = (4-tmpC)%4;
int tmpD = (src[3] + container[0] + container[3] + container[4])%4;
int tmpF = (src[5] + container[2] + container[4] + container[5])%4;
container[6] = (4-tmpD)%4;
container[8] = (4-tmpF)%4;
//检查E的状态及GHI
int E = (src[4] + container[0] + container[2] + container[4] + container[6] + container[8])%4;
if (E != 0)
return false;
int tmpG = (src[6] + container[3] + container[6])%4;
int tmpH = (src[7] + container[4] + container[6] + container[8])%4;
int tmpI = (src[8] + container[5] + container[8])%4;
if (tmpG != tmpH || tmpH != tmpI)
return false;
container[7] = (4-tmpI)%4;
return true;
}
void getMinOper(int * container, int * src, int& min)
{
int tmpContainer[10] = {0};
int tmp = 0;
do {
if (getCurOper(tmpContainer, src, tmp)) {
if (tmp < min) {
min = tmp;
for (int i=0;i<9;++i)
container[i] = tmpContainer[i];
}
}
}while(getNextCond(tmpContainer));
}
int main(){
int min = 99999;
int contain[9];
for (int i=0;i<9;i++) {
cin>>A[i];
}
if (isClock(A)) {
cout<<"0"<<endl;
return 0;
}
getMinOper(contain, A, min);
for (int i=0;i<9;++i) {
while (contain[i]--) {
printf("%d ",i+1);
}
}
return 0;
}