Flip Game
Description Flip game is played on a rectangular 4x4 field with two-sided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. Each round you flip 3 to 5 pieces, thus changing the color of their upper side from black to white and vice versa. The pieces to be flipped are chosen every round according to the following rules:
bwbw wwww bbwb bwwb Here "b" denotes pieces lying their black side up and "w" denotes pieces lying their white side up. If we choose to flip the 1st piece from the 3rd row (this choice is shown at the picture), then the field will become: bwbw bwww wwwb wwwb The goal of the game is to flip either all pieces white side up or all pieces black side up. You are to write a program that will search for the minimum number of rounds needed to achieve this goal. Input The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position.
Output Write to the output file a single integer number - the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it's impossible to achieve the goal, then write the word "Impossible" (without quotes).
Sample Input bwwb bbwb bwwb bwww Sample Output 4 Source 1 #include<stdio.h> 2 #include<iostream> 3 using namespace std; 4 bool a[6][6] = {false} ; 5 int r[] = {-1 , 1 , 0 , 0 , 0} ; 6 int c[] = {0 , 0 , -1 , 1 , 0} ; 7 bool flag ; 8 int step ; 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] != a[1][1]) 15 return false ; 16 } 17 } 18 return true ; 19 } 20 21 void flip (int row , int col) 22 { 23 for (int i = 0 ; i < 5 ; i++) { 24 a[row + r[i]][col + c[i]] = !a[row + r[i]][col + c[i]] ; 25 } 26 } 27 28 void dfs (int row , int col , int deep) 29 { 30 if (deep == step) { 31 flag = judge_all () ; 32 return ; 33 } 34 35 if (flag || row == 5) 36 return ; 37 38 flip (row , col) ; 39 if (col < 4) 40 dfs (row , col + 1 , deep + 1) ; 41 else 42 dfs (row + 1 , 1 , deep + 1) ; 43 // printf ("row = %d, col = %d, deep = %d " , row , col , deep) ; 44 flip (row , col) ; 45 if (col < 4) 46 dfs (row , col + 1 , deep) ; 47 else 48 dfs (row + 1 , 1 , deep) ; 49 50 return ; 51 } 52 53 int main () 54 { 55 // freopen ("a.txt" , "r" , stdin) ; 56 char x ; 57 for (int i = 1 ; i < 5 ; i++) { 58 for (int j = 1 ; j < 5 ; j++) { 59 cin >> x ; 60 if (x == 'b') 61 a[i][j] = 1 ; 62 } 63 } 64 65 for (step = 0 ; step <= 16 ; step++) { 66 dfs ( 1 , 1 , 0) ; 67 if (flag) 68 break ; 69 } 70 /*step = 2 ; 71 dfs ( 1 , 1 , 0) ;*/ 72 73 if (flag) 74 printf ("%d " , step) ; 75 else 76 printf ("Impossible ") ; 77 78 return 0 ; 79 } 不得不说用递归写很有诀窍的,感觉这道题就是把暴力写成了递归。(虽然叫dfs) cin 原来不收 “换行符” 。 思路: 最少0步, 最多16步。先检查0步,再1步 , 2步……,以此类推。 转载:http://www.cnblogs.com/lyy289065406/archive/2011/07/29/2120501.html |