您的位置:首页 > 其它

POJ 1753 Flip Game

2016-08-31 17:12 423 查看
Description

Flip game is played on a rectangular 4x4 field with two-sided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. Each round you flip 3 to 5 pieces,
thus changing the color of their upper side from black to white and vice versa. The pieces to be flipped are chosen every round according to the following rules: 
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

The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position.
Output

Write to the output file 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).
Sample Input
bwwb
bbwb
bwwb
bwww

Sample Output
4


这题的大意就是给你一个4*4的棋盘,上面摆放着只有黑白两面的棋子,然后让你用最少的步数把棋盘变成只有白面向上或只有黑面向上的状态,输出最少的步数。

因为数据比较小,可以状态压缩一下,直接BFS。

记录棋盘的状态,达到0或者(1<<16)-1时就可以输出步数。

#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn = (1<<16) - 1;
int dir[5][2] = {1,0,0,1,-1,0,0,-1,0,0};
char a[10][10];
int b[maxn+10];
struct node
{
int x,s;
};
void bfs(int sum)
{
int i,j,k;
memset(b,0,sizeof(b));
queue<node> q;
node p,t;
t.x = sum;
t.s = 0;
q.push(t);
b[sum] = 1;
while(!q.empty())
{
t = q.front();
q.pop();
if(t.x == 0 || t.x == maxn)
{
printf("%d\n",t.s);
return;
}
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
int x = t.x;
for(k=0;k<5;k++)
{
int tx = i + dir[k][0];
int ty = j + dir[k][1];
if(tx < 0 || tx > 3 || ty < 0 || ty > 3)
continue;
int l = tx*4 + ty;
x ^= (1 << l);
}
if(!b[x])
{
p.x = x;
p.s = t.s + 1;
b[x] = 1;
q.push(p);
}
}
}
printf("Impossible\n");
}
int main(void)
{
int i,j;
for(i=0;i<4;i++)
scanf("%s",a[i]);
int c = 0;
int sum = 0;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
if(a[i][j] == 'b')
{
sum += (1 << c);
}
c++;
}
bfs(sum);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: