您的位置:首页 > 其它

POJ 1753 - Flip Game (位运算 + BFS)

2016-08-29 21:31 525 查看

题目链接:

http://poj.org/problem?id=1753

题意:

给一个4x4的棋盘,每次可以翻其中一个棋子,这个棋子上下左右的棋子也会被翻过来,问何时可以达到全白或全黑的状态。

题解:

此题可以将棋盘上的状态转化为一个数字去存。将棋盘上状态看成一个2进制的数,1代表黑色0代表白色,可以翻的16个地方记做移动步数,这样只要把每次状态与这16种走法作异或运算即是翻过去的下一种状态。

BFS即可。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

struct Node
{
int state, step;
};

int vis[65536];

int mov[16] =   //16种状态转换,对应4*4的翻子位置
{
51200,58368,29184,12544,
35968,20032,10016,4880,
2248,1252,626,305,
140,78,39,19
};

int bfs(int state)
{
queue <Node> q;
memset(vis,0,sizeof(vis));
Node cur,next;
cur.state = state;
cur.step = 0;
q.push(cur);
vis[cur.state] = 1;
while(!q.empty())
{
cur = q.front();
q.pop();
if(cur.state == 0 || cur.state == 65535)
return cur.step;
for(int i = 0; i < 16; i++)
{
next.state = cur.state ^ mov[i];
next.step = cur.step + 1;
if(vis[next.state])
continue;
if(next.state == 0 || next.state == 65535)
return next.step;
vis[next.state] = 1;
q.push(next);
}
}
return -1;
}

int main()
{
char ch[5][5];
while(~scanf("%s",ch[0]))
{
for(int i = 1 ; i < 4 ; i++)
scanf("%s",ch[i]);
int state = 0,bits = 0;
for(int i = 3 ; i >= 0 ; i--)
{
for(int j = 3 ; j >= 0 ; j--)
{
if(ch[i][j] == 'b')
state += (1 << bits);
bits++;
}
}
int ans = bfs(state);
if(ans == -1)
puts("Impossible");
else
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm