Flip Game
题目链接:
http://poj.org/problem?id=1753
解题思路:
题目大意:
有一个4*4的方格,每个方格中放一粒棋子,这个棋子一面是白色,一面是黑色。游戏规则为每次任选16颗中的一颗,把选中的这颗
以及它四周的棋子一并反过来,当所有的棋子都是同一个颜色朝上时,游戏就完成了。现在给定一个初始状态,要求输出能够完成
游戏所需翻转的最小次数,如果初始状态已经达到要求输出0。如果不可能完成游戏,输出Impossible。
算法思想:
先假设前一个状态为:
wwww
wwww
wwww
wwww
即二进制表示为0000 0000 0000 0000,十进制对应为0。若此时选定左上角第一个棋子进行操作,根据规则,它右边和下边的也要
同时进行变换(因为其左边和上边为空,不做考虑),之后,相应的状态用二进制表示,应变为:1100 1000 0000 0000,十进制值为
51200。这个过程相当于对十进制数51200进行对十进制数0的异或操作,即next=0^(51200),而51200这个数则可以根据对十进制
数1进行相应的左移操作得到。同时,我们知道,棋牌总共有16个位置,也就是说相应的不同的操作也有16种,即有16个不同的数
经过异或操作用来改变前一个状态的值。那么,先将这16个数枚出来得到change数组。代码如下:
#include <iostream>
#include <cstdio>
using namespace std;
const int dx[] = {-1,0,1,0},dy[] = {0,-1,0,1};
void init(){
int tmp;
for(int i = 0; i < 4; ++i){
for(int j = 0; j < 4; ++j){
tmp = 0;
tmp ^= (1<<((3-i)*4+3-j)); //第一行代表16位的高4位,同理第一列也代表高位,所以棋盘(i,j)处在16位中的位置是((3-i)*4+3-j)
//temp ^= (1<<(15 - ( i*4 + j )));
for(int k = 0; k < 4; ++k){
int x = i + dx[k];
int y = j + dy[k];
if(x<0 || y<0 || x>3 || y>3)
continue;
tmp ^= (1<<((3-x)*4+3-y));
}
cout<<tmp<<" ";
}
cout<<endl;
}
}
int main(){
init();
return 0;
}
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node{
int state;
int step;
};
bool vis[65536];
int change[16] = {
//16种状态转换,对应4*4的翻子位置
51200,58368,29184,12544,
35968,20032,10016,4880,
2248,1252,626,305,
140,78,39,19
};
int bfs(int state){
memset(vis,false,sizeof(vis)); //标记每一个状态都未访问过
queue<node> q;
node cur,next;
cur.state = state;
cur.step = 0;
q.push(cur);
vis[state] = true;
while(!q.empty()){
cur = q.front();
q.pop();
if(cur.state == 0 || cur.state == 0xffff) //65535
return cur.step;
for(int i = 0; i < 16; ++i){
next.state = cur.state^change[i];
next.step = cur.step + 1;
if(vis[next.state])
continue;
if(next.state == 0 || next.state == 0xffff) //65535
return next.step;
vis[next.state] = true;
q.push(next);
}
}
return -1;
}
int main(){
int state,ans;
char ch[5][5];
while(~scanf("%s",ch[0])){
for(int i = 1 ; i < 4 ; ++i)
scanf("%s",ch[i]);
state = 0;
for(int i = 0 ; i < 4 ; ++i){
for(int j = 0 ; j < 4 ; ++j){
state <<= 1;
if(ch[i][j] == 'b')
state += 1;
//state ^= (1<<((3-i)*4+(3-j)));
}
}
ans = bfs(state);
if(ans == -1)
puts("Impossible");
else
printf("%d\n",ans);
}
return 0;
}