The game “The Pilots Brothers: following the stripy elephant” has a quest where a player needs to open a refrigerator.
There are 16 handles on the refrigerator door. Every handle can be in one of two states: open or closed. The refrigerator is open only when all handles are open. The handles are represented as a matrix 4х4. You can change the state of a handle in any location [i, j] (1 ≤ i, j ≤ 4). However, this also changes states of all handles in row i and all handles in column j.
The task is to determine the minimum number of handle switching necessary to openhe the refrigerator.
在poj 1753的基础上增加了路径保存,递归输出即可。
#include<iostream>
#include<limits.h>
#include<string.h>
using namespace std;
int sta=0;
bool mi[65536];
short int st[65536];
int ori[65536];
bool is_end(int status,int step){
if (status==0) {
cout<<step<<endl;
return(true);
}
else return(false);
}
int work2(int n,int status){
int tt=1<<n;
return(status^tt);
}
int work(int n,int status){
int temp=status;
int ii=n/4,jj=n%4;
for (int i=0;i<4;i++)temp=work2(i*4+jj,temp);
for (int i=0;i<4;i++)temp=work2(ii*4+i,temp);
temp=work2(n,temp);
return(temp);
}
void bfs(int status){
int head=0,tail=0,temp,step,temp_status;
int que1[65536],que2[65536];
bool t1=true;
que1[0]=status;que2[0]=0;
while (head<=tail){
temp=que1[head];
step=que2[head];
head++;
for (int i=15;i>=0;i--){
temp_status=work(i,temp);
if (!mi[temp_status]){
mi[temp_status]=true;
st[temp_status]=i;
ori[temp_status]=temp;
tail++;
que1[tail]=temp_status;
que2[tail]=step+1;
}
if (is_end(temp_status,step+1)) {
t1=false;
break;
}
}
if (!t1) break;
}
if (t1) cout<<"Impossible"<<endl;
}
void print(int status){
if (status!=sta){
print(ori[status]);
cout<<(4-st[status]/4)<<' '<<(4-st[status]%4)<<endl;
}
}
int main(){
char ch;
memset(mi,sizeof(mi),false);
for(int i=0;i<16;i++){
cin>>ch;
sta=sta<<1;
sta+=(ch=='+');
}
mi[sta]=true;
bfs(sta);
print(0);
return 0;
}