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
用位运算存每一个方格的中棋子的状态,这样就会有65536种状态, ‘b’为0,‘w’为1,然后再找到当前的起始状态对应的数,然后从当前状态开始广搜,直到搜到全黑或全白的状态停止。这道题用到了基本的位运算,通过这道题学到了不少位运算的知识
//代码是看了别人的,然后理解了写下来的
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
int num;
const int white=(1<<16)-1;
const int black=0;
bool vis[1<<16];
struct node
{
int state;
int cnt;
};
struct node now,temp;
//记录下当前状态所对应的位置
bool bit()
{
int i,j;
char ch;
num=0;
int count=0;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
cin>>ch;
if(ch=='w')
num+=(1<<count);
count++;
}
if(num==white||num==black)
{
printf("0/n");
return true;
}
return false;
}
//实现任意一步反转
void Flip(int x,int y)
{
now.state^=1<<(4*x+y);
if(x==0)
now.state^=1<<(4+y);
else if(x==3)
now.state^=1<<(4*2+y);
else
{
now.state^=1<<4*(x-1)+y;
now.state^=1<<4*(x+1)+y;
}
if(y==0)
now.state^=1<<4*x+1;
else if(y==3)
now.state^=1<<4*x+2;
else
{
now.state^=1<<4*x+y-1;
now.state^=1<<4*x+y+1;
}
}
//遍历所有状态
void bfs()
{
queue<struct node> q;
vis[temp.state]=1;
q.push(temp);
while(!q.empty())
{
temp=q.front();
q.pop();
temp.cnt++;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
now=temp;
Flip(i,j);
if(now.state==white||now.state==black)
{
cout<<now.cnt<<endl;
return;
}
if(!vis[now.state])
{
vis[now.state]=1;
q.push(now);
}
}
}
cout<<"Impossible"<<endl;
}
int main()
{
if(!bit())
{
temp.state=num;
temp.cnt=0;
bfs();
}
return 0;
}