您的位置:首页 > 其它

poj 1753 Flip Game

2013-08-18 11:45 260 查看
点击打开链接

Flip Game

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 25674Accepted: 11093
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


题目大意就是给一个棋盘,每次可以选一个点进行一次操作,操作的方法就是:把这个点和这个点上下左右的四个点的颜色反一下,就是黑变成白,白变成黑,问最少多少步整个棋盘能变成一个颜色

广度优先搜索,需要注意的是把一个棋盘压缩成一个整数,每一位代表棋盘上的一个棋子,这样就涉及到了位操作,
#include<stdio.h>
#include<queue>
using namespace std;

queue<int> q;
bool flag[0x10000];
int step[0x10000];
int calculate(int num, int i)
{
int p = 1<< i;
if(i % 4 != 0)
p |= 1<<(i - 1);
if((i + 1) % 4 != 0)
p |= 1 <<(i + 1);
if(i > 3)
p |= 1 <<(i - 4);
if(i < 12)
p |= 1 <<(i + 4);
return num ^ p;
}
int bfs()
{
while(!q.empty())
{
int num = q.front();
q.pop();
int i;
for(i = 0; i < 16; i++)
{
int new_num = calculate(num, i);

if(flag[new_num] != 1)
{
if(new_num == 0 || new_num == 0xffff)
return step[num] + 1;
q.push(new_num);
flag[new_num] = 1;
step[new_num]  = step[num] + 1;
}
}
}
return -1;
}
int main()
{
char ch;
int num = 0;
int i = 16;
//	freopen("test.txt", "r", stdin);
while(i--)
{
scanf("%c", &ch);
//		memset(flag, 0, sizeof(flag));
if(ch == '\n' || ch == ' ')
{
i++;
continue;
}
num <<= 1;
if(ch == 'w')
num++;
}
flag[num] =1;
q.push(num);
step[num] = 0;
if(num == 0 || num == 0xffff)
{
printf("0\n");
return 0;
}
int t = bfs();
if(t != -1)
printf("%d\n", t);
else
printf("Impossible\n");

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