POJ

来源:互联网 发布:linux虚拟机home扩容 编辑:程序博客网 时间:2024/04/30 03:49
题目链接:http://poj.org/problem?id=1753
题解:状态压缩bfs()
方格为4*4所以状态最多有2^16
int 可以表示,0为全黑,65535为全白
从起始状态开始bfs过程中判断是否搜到0或65535
关键是进行状态的转换,使用亦或操^,每次改变该位的数字,到相反。
其中0表示黑,1表示白
代码如下:

#include<iostream>#include<cstdio>#include<string>#include<string.h>#include<queue>#include<stdlib.h>using namespace std;char map[5][5];struct node{ int step,num;} cur;node tem,tem1;int temp;int flag;int vis[65540];queue<node>p;void bfs(){ int i,j,k; vis[temp]=1; while(!p.empty()) p.pop(); cur.num=temp; cur.step=0; p.push(cur); while(!p.empty()) { tem=p.front(); p.pop(); if(tem.step>=16) { // printf("Impossible"); return ; } tem1.step=tem.step+1; for(i=0; i<16; i++) { temp=i; tem1.num=tem.num^(1<<temp); if(temp+4<16) { tem1.num=tem1.num^(1<<(temp+4)); } if(temp-4>=0) { tem1.num=tem1.num^(1<<(temp-4)); } if(temp%4!=0) tem1.num=tem1.num^(1<<(temp-1)); if(temp%4!=3) tem1.num=tem1.num^(1<<(temp+1)); if(tem1.num==65535||tem1.num==0) { printf("%d",tem1.step); flag=1; return ; } if(vis[tem1.num]!=1) { p.push(tem1); vis[tem1.num]=1; } } }}int main(){ int i,j,k; flag=0; for(i=0; i<4; i++) { scanf("%s",&map[i]); } k=0; memset(vis,0,sizeof(vis)); for(i=0; i<4; i++) { for(j=0; j<4; j++) { if(map[i][j]=='w') { k+=(1<<(i*4+j)); } } } temp=k; vis[temp]=1; if(temp==65535||temp==0) { printf("0"); return 0; } else { bfs(); if(flag==0) printf("Impossible"); } return 0;}

0 0