BFS之一

//poj 1166 The Clocks

#include
<iostream> //BFS 51808K 516MS
#include<string>
using namespace std;
string str[10]={" ","ABDE","ABC","BCEF","ADG","BDEFH","CFI","DEGH","GHI","EFHI"};
// A 对应 state[0][0], B 对应 state[0][1],I 对应 state[3][3]
struct node{
int state[3][3];
int path[40],r; //如果用string来记录路径则 MLE,开string比较浪费空间
//r表示步数,path记录路径
}table[1000000];
bool vis[500000]; //记忆化搜索,否则会爆内存,例如: 3 3 3 3 3 3 3 3 3
int hash(int a[3][3]) //离散化记录表盘的状态
{
int s=1,t=1;
for(int i=0;i<3;++i)
for(int j=0;j<3;++j)
s
+=a[i][j]*t,t*=4;
return s;
}
int main()
{
int head=0,rear=0,tag=1;
for(int i=0;i<3;++i)
for(int j=0;j<3;++j)
scanf(
"%d",&table[0].state[i][j]);
table[
0].r=-1; //路径path[0..r],所以步数 r 初始化为 -1
vis[hash(table[0].state)]=1;
while(1)
{
for(int k=1;k<10;++k) //分别对应九种变换
{
rear
++;
for(int i=0;i<3;++i)
for(int j=0;j<3;++j)
table[rear].state[i][j]
=table[head].state[i][j];
for(int l=0;l<str[k].length();++l)
{
int m=str[k][l]-'A';
table[rear].state[m
/3][m%3]=(table[rear].state[m/3][m%3]+1)%4;
//state[i][j]的状态是0,1,2,3 之一,分别表示12点,3点,6点,9点
}
if(vis[hash(table[rear].state)]==1)
{
rear
--;continue;
}
vis[hash(table[rear].state)]
=1;
table[rear].r
=table[head].r+1; //步数加 1
for(int l=0;l<=table[head].r;++l)
table[rear].path[l]
=table[head].path[l];
table[rear].path[table[rear].r]
=k; //更新路径
tag=1;
for(int i=0;i<3&&tag;++i)
for(int j=0;j<3&&tag;++j)
if(table[rear].state[i][j]!=0)
tag
=0;
if(tag==1) //all the dials to 12 o'clock
{
for(int l=0;l<=table[rear].r;++l)
printf(
"%d ",table[rear].path[l]);
printf(
"\n");

return 0;
}
}
head
++;
}
}

  

posted on 2011-08-22 11:58  sysu_mjc  阅读(136)  评论(0编辑  收藏  举报

导航