The Pilots Brothers' refrigerator(dfs)
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 19718 | Accepted: 7583 | Special Judge |
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
Source
1 #include<stdio.h> 2 #include<iostream> 3 using namespace std; 4 bool a[6][6] = {0} ; 5 bool flag ; 6 int step ; 7 int in[40] ; 8 int dex ; 9 10 bool judge_all () 11 { 12 for (int i = 1 ; i < 5 ; i++) { 13 for (int j = 1 ; j < 5 ; j++) { 14 if (a[i][j]) 15 return false ; 16 } 17 } 18 return true ; 19 } 20 21 void flip (int row , int col) 22 { 23 for (int i = 1 ; i < 5 ; i++) { 24 a[row][i] = !a[row][i] ; 25 a[i][col] = !a[i][col] ; 26 } 27 a[row][col] = !a[row][col] ; 28 } 29 30 void dfs (int row , int col , int deep) 31 { 32 if (deep == step) { 33 flag = judge_all (); 34 return ; 35 } 36 37 if (flag || row == 5) 38 return ; 39 40 flip (row , col) ; 41 if (col < 4) 42 dfs (row , col + 1 , deep + 1) ; 43 else 44 dfs (row + 1 , 1 , deep + 1) ; 45 46 flip (row , col) ; 47 if (flag) { 48 in[dex] = row ; 49 in[dex + 1] = col ; 50 dex += 2 ; 51 } 52 if (col < 4) 53 dfs (row , col + 1 , deep) ; 54 else 55 dfs (row + 1 , 1 , deep) ; 56 57 return ; 58 } 59 60 int main () 61 { 62 // freopen ("a.txt" , "r" , stdin) ; 63 char x ; 64 for (int i = 1 ; i < 5 ; i++) { 65 for (int j = 1 ; j < 5 ; j++) { 66 cin >> x ; 67 if ( x == '+') 68 a[i][j] = 1 ; 69 } 70 } 71 72 for (step = 1 ; step <= 16 ; step++) { 73 dex = 1 ; 74 dfs (1 , 1 , 0) ; 75 if (flag) 76 break ; 77 } 78 79 printf ("%d\n" , step) ; 80 for (int i = step * 2; i >= 1 ; i--) { 81 if ( i & 1) 82 printf ("%d %d\n" , in[i] , in[i + 1]) ; 83 } 84 }
套Flip Game 模板,思路也一样