Description
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 open the refrigerator.
Input
The input contains four lines. Each of the four lines contains four characters describing the initial state of appropriate handles. A symbol “+” means that the handle is in closed state, whereas the symbol “−” means “open”. At least one of the handles is initially closed.
Output
The first line of the input contains N – the minimum number of switching. The rest N lines describe switching sequence. Each of the lines contains a row number and a column number of the matrix separated by one or more spaces. If there are several solutions, you may give any one of them.
Sample Input
-+-- ---- ---- -+--
Sample Output
6 1 1 1 3 1 4 4 1 4 3 4 4
题目大意:
开冰箱,有16个把柄,每个把柄有打开和关闭两个状态,每打开一个把柄,同一行和同一列的把柄就会同时改变状态,打开变关闭,关闭变打开,求最少需要多少步?,并记下过程。
解题思路:
和Flip Game 枚举一样 ,只是加了个过程。BFS
#include <stdio.h> #include <string.h> #define max 65536 int queue[max*2]; int visit[max],step[max]; int prei[max],prej[max],pre[max]; int m,n,k,x[max],y[max]; int flag; int main(){ int i,j; char str; int id=0,tmp; int f=0,r=0; memset(pre,-1,sizeof(pre)); for(i=0;i<4;++i) for(j=0;j<4;++j){ scanf(" %c",&str); id<<=1; if(str=='+') id+=1; //1为+,0为- } if(id==0){ printf("0\n"); return 0; } queue[r++]=id; visit[id]=1; while(f<r){ id=queue[f++]; for(i=0;i<=3;++i) for(j=0;j<=3;++j){ tmp=id; tmp^=1<<(15-j); tmp^=1<<(15-j-4); tmp^=1<<(15-j-8); tmp^=1<<(15-j-12); tmp^=1<<(15-4*i); tmp^=1<<(15-4*i-1); tmp^=1<<(15-4*i-2); tmp^=1<<(15-4*i-3); tmp^=1<<(15-4*i-j);//(i,j)多翻了一次 if(!visit[tmp]){ queue[r++]=tmp; prei[tmp]=i+1; prej[tmp]=j+1; pre[tmp]=id; visit[tmp]=1; step[tmp]=step[id]+1; } if(tmp==0){ printf("%d\n",step[id]+1); m=n=step[id]+1; while(pre[tmp]!=-1){ x[n--]=prei[tmp]; y[m--]=prej[tmp]; tmp=pre[tmp]; } for(k=1;k<=step[id]+1;++k){ printf("%d %d\n",x[k],y[k]); } return 0; } } } return 0; }