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
The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position.
Output
Write to the output 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).
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Sample Input
2
bwbw
wwww
bbwb
bwwb
bwwb
bbwb
bwwb
bwww
Sample Output
Impossible
4
这个题,第一次看的时候完全没有思路,虽然知道是用bfs来做,可是不知道怎么来建模型,实现这个过程,甚至对那个状态的判断都不是很明白,后来想想才明白,
此题目的是达到全白,或者全黑,从当前第一个棋盘模式开始,搜索,从当前开始,在键盘上任意操作一次就是一个状态,就算作上个节点的邻接点,所以,大致思路就是明白了,具体实现的时候,才感觉到这个题,关键点是,怎么实现标记,以及怎么实现每一步的操作,都是关键点。每个状态都对应一个数字,如果看成二进制的话,可以求出来,但是该值出队列的时候,怎么把它还原以及怎么找它的下一个邻接点是个耐人寻味的事情。
当然了,开始时候是没有觉悟到用,位运算来操作的,都是觉得别的方法太麻烦,才不得不想出这个做法。
位运算,其实很简单,只不过是我们平时用的较少罢了。
#include
#include
#include
#include
#include
using namespace std;
bool staus[65536];
char map[4][4];
int bottom[4][4];
int drex[4]={-1,0,1,0};
int drey[4]={0,1,0,-1};
bool Moveable(int x,int y){
if(x<0||x>3||y<0||y>3)
return false;
return true;
}
typedef struct node{
int data;
int floor;
}node;
queue test;
int main(){
int N,i,j,start,posion,case1=0;
node startnode,temp,nextnode;
scanf("%d",&N);
while(N--){
int key=0;
start=0;
case1++;
memset(staus,0,sizeof(staus));
for(i=0;i<4;i++){
scanf("%s", map[i]);
for(j=0;j<4;j++){
if(map[i][j]=='w')bottom[i][j]=1;
else bottom[i][j]=0;
start+=bottom[i][j]*(int)pow(2.0,(i*4+j)*1.0);
}
}
startnode.data=start;
startnode.floor=0;
staus[start]=true;
test.push(startnode);
while(!test.empty()){
temp=test.front();
test.pop();
if(temp.data==65535||temp.data==0){
printf("%d\n",temp.floor);
key=1;
break;
}
for(posion=0;posion<16;posion++){
nextnode.data=temp.data^(1<