Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 41203 | Accepted: 17892 |
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
状态压缩+BFS,暴力枚举每种情况,题目不难,但还是参考了题解,是个不错的练习。代码如下:
#include<iostream>
using namespace std;
int rear=0,top=0;
int step[65536]={0},qstate[65536]={0};
bool r[65536]={0};
void init()
{
int temp=0;
char a[10];
for(int i=0;i<4;++i)
{
cin>>a;
for(int j=0;j<4;++j)
{ if(a[j]=='b') temp|=(1<<(i*4)+j);
}
}
qstate[rear++]=temp;
}
int change(int state,int i)
{
int temp=0;
temp|=(1<<i);
if(i%4!=0) temp|=(1<<(i-1));
if((i+1)%4!=0) temp|=(1<<(i+1));
if(i+4<16) temp|=(1<<(i+4));
if(i-4>0) temp|=(1<<(i-4));
return (state^temp);
}
bool BFS()
{
while(top<rear)
{
int state=qstate[top++];
for(int i=0;i<16;++i)
{
int temp;
temp=change(state,i);
if(state==0||state==65535)
{
cout<<step[state];
return true;
}
else if(!r[temp])
{
qstate[rear++]=temp;
r[temp]=true;
step[temp]=step[state]+1;
}
}
}
return false;
}
int main()
{
init();
if(!BFS()) cout<<"Impossible"<<endl;
return 0;
}