poj1753 Flip Game
看成是一棵深度为16的树,每一个格子有两个状态,flip或non-flip,构成一棵二叉树。深搜这棵树就可以得到结果
最少的轮数,可以给深搜加一条件: flip step次的时候,检查是否完成,step从0~16,这样就可以得到最少的轮数了。感觉可以用宽搜
View Code
1 #include <stdio.h> 2 bool chess[5][5]; 3 int step; 4 void flip(int row,int col) 5 { 6 chess[row][col]=!chess[row][col]; 7 if(row-1>0) 8 chess[row-1][col]=!chess[row-1][col]; 9 if(col+1<=4) 10 chess[row][col+1]=!chess[row][col+1]; 11 if(row+1<=4) 12 chess[row+1][col]=!chess[row+1][col]; 13 if(col-1>0) 14 chess[row][col-1]=!chess[row][col-1]; 15 } 16 bool checkAll() 17 { 18 int i,j; 19 bool t=chess[1][1]; 20 for(i=1;i<=4;i++) 21 for(j=1;j<=4;j++) 22 if(chess[i][j]!=t) 23 return false; 24 return true; 25 } 26 void print() 27 { 28 int i,j; 29 for(i=1;i<=4;i++) 30 { 31 for(j=1;j<=4;j++) 32 { 33 if(chess[i][j]) 34 printf("w"); 35 else 36 printf("b"); 37 } 38 printf("\n"); 39 } 40 printf("\n"); 41 } 42 bool dfs(int row,int col,int deep) 43 { 44 // print(); 45 if(deep==step) 46 return checkAll(); 47 if(row==5) 48 return false; 49 flip(row,col); //current row,col flip 50 bool status=false; 51 if(col<4) 52 status=dfs(row,col+1,deep+1); 53 else 54 status=dfs(row+1,1,deep+1); 55 if(status==true) 56 return true; 57 58 flip(row,col); //current row,col not flip 59 if(col<4) 60 status=dfs(row,col+1,deep); 61 else 62 status=dfs(row+1,1,deep); 63 if(status==true) 64 return true; 65 return false; 66 } 67 int main() 68 { 69 char row[5]; 70 int i,j; 71 72 for(i=1;i<=4;i++) 73 { 74 scanf("%s",row); 75 for(j=0;j<4;j++) 76 { 77 if(row[j]=='w') //while is true, black is false. 78 chess[i][j+1]=true; 79 else 80 chess[i][j+1]=false; 81 } 82 } 83 for(step=0;step<=16;step++) 84 { 85 if(dfs(1,1,0)==true) 86 { 87 printf("%d\n",step); 88 break; 89 } 90 } 91 if(step>16) 92 printf("Impossible\n"); 93 return 0; 94 }


浙公网安备 33010602011771号