Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 28870 | Accepted: 12497 |
Description
- Choose any one of the 16 pieces.
- Flip the chosen piece and also all adjacent pieces to the left, to the right, to the top, and to the bottom of the chosen piece (if there are any).
Consider the following position as an example:
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
Output
Sample Input
bwwb bbwb bwwb bwww
Sample Output
4
题目大意: 一个有正反两面的纸,求最少翻转几次使得最终4*4的方格纸全为黑面或者全为白面
附上AC代码:
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int vis[(1<<16)-1],step[(1<<16)-1]; //vis表示当前id是否已经历遍,step表示当前id下的翻转次数
int bfs(int id){
if(id==0 || id==(1<<16)-1){ //最终情况要么 id==0 或者 1111 1111 1111 1111(二进制下)
cout<<'0'<<endl;
return 1;
}
memset(vis,0,sizeof(vis));
queue <int> q;
while(!q.empty())
q.pop();
q.push(id);
vis[id]=1;
//从当前id出发bfs,历遍所有的情况
while(!q.empty()){
int tmp=q.front();
q.pop();
id=tmp;
//16个方格分别翻转一次,按照规则再在各自的基础上接着翻转,直到成功为止
for(int i=0;i<4;i++)
for(int j=0;j<4;j++){ //i j从0 0 到3 3 对应 id从高位到低位 与1异或表示对当前位取反,即0 ^ 1=1 1 ^ 1=0;
tmp=id;
if(i==0)
tmp^=1<<(11-j); //将 i+1,j 对应的那一位取反
else if(i==1){
tmp^=1<<(15-j); //将 i-1,j ...
tmp^=1<<(7-j); //将 i+1,j ...
}
else if(i==2){
tmp^=1<<(11-j);
tmp^=1<<(3-j);
}
else if(i==3)
tmp^=1<<(7-j); //将i-1,j ...
if(j==0) // 将相应位置对应数字取反 ,自己在纸上画一遍应该就很容易明白了
tmp^=3<<(14-4*i); //3 在二进制里即 11
else if(j==1)
tmp^=7<<(13-4*i); //7 在二进制里即 111
else if(j==2)
tmp^=7<<(12-4*i);
else if(j==3)
tmp^=3<<(12-4*i);
if(tmp==0 || tmp==(1<<16)-1){ //满足情况输出 并 退出程序
cout<<step[id]+1<<endl;
return 1;
}
if(!vis[tmp]){ //当前tmp格局未访问,进入队列
step[tmp]=step[id]+1;
q.push(tmp);
vis[tmp]=1;
}
}
}
return 0;
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
char ch;
int id=0; // id用来表示当前输入的方格布局 ,例如题目里的输入布局,
//则在二进制下的 id= 1001 1101 1001 1000 即为当前布局
//注意左边为高位,右边为低位,后面bfs时要特别注意
for(int i=0;i<16;i++){
cin>>ch;
id<<=1; //左移一位的位运算,十进制里相当于乘以2
if(ch=='b'){
id+=1;
}
}
if(!bfs(id))
cout<<"Impossible"<<endl;
return 0;
}