poj 2965 The Pilots Brothers' refrigerator
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个开关,‘-’表示打开,‘+’表示关闭,当十六个开关都打开的时候,冰箱才能打开.
这道题和poj 1753类似,但要注意翻棋是整行整列的翻。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <stdio.h> 3 using namespace std; 4 bool chess[6][6]= {{false}}; 5 int step; 6 bool flag; 7 int cot; 8 int ans[50]; 9 bool reach_all() //判断是否为一种颜色 10 { 11 for(int i=1; i<5; i++) 12 { 13 for(int j=1; j<5; j++) 14 { 15 if(chess[i][j]) 16 return false; 17 } 18 } 19 return true; 20 } 21 void turn(int row,int col) //翻棋 22 { 23 for(int i=1; i<5; i++) 24 { 25 chess[row][i]=!chess[row][i]; 26 chess[i][col]=!chess[i][col]; 27 } 28 chess[row][col]=!chess[row][col]; 29 } 30 void dfs(int row,int col,int deep) // 深搜迭代回溯很重要 31 { 32 if(deep==step) 33 { 34 flag=reach_all(); 35 return ; 36 } 37 if(flag||row==5) 38 return ; 39 turn(row,col); //翻棋 40 if(col<4) 41 dfs(row,col+1,deep+1); 42 else 43 dfs(row+1,1,deep+1); 44 turn(row,col); //不符合则翻回来 45 if(flag) 46 { 47 ans[cot++]=row; 48 ans[cot++]=col; 49 } 50 if(col<4) 51 dfs(row,col+1,deep); 52 else 53 dfs(row+1,1,deep); 54 return ; 55 } 56 int main() 57 { 58 char ch; 59 for(int i=1; i<5; i++) 60 { 61 for(int j=1; j<5; j++) 62 { 63 scanf("%c",&ch); 64 if(ch=='+') 65 chess[i][j]=true; 66 } 67 getchar(); 68 } 69 for(step=1; step<=16; step++) //枚举每一种情况 70 { 71 cot=1; 72 dfs(1,1,0); 73 if(flag) 74 break; 75 } 76 printf("%d\n",step); 77 for(int i=step*2; i>=1; i--) 78 if(i&1) 79 printf("%d %d\n",ans[i],ans[i+1]); 80 return 0; 81 }