1 10 *........X 1 3 *#X 3 20 #################### #XY.gBr.*.Rb.G.GG.y# #################### 0 0
Escape possible in 9 steps. The poor student is trapped! Escape possible in 45 steps.
//109MS 556K #include<stdio.h> #include<queue> #include<string.h> #include<algorithm> #define M 107 using namespace std; int n,m,s,t; int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}}; char g[M][M]; bool vis[M][M][17]; char up[4]={'B','Y','R','G'}; char low[4]={'b','y','r','g'}; struct node { int step,x,y,key; }; int bfs() { queue<node>q; node now,next; now.x=s;now.y=t;now.step=now.key=0; vis[s][t][0]=true; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); if(g[now.x][now.y]=='X')return now.step; for(int i=0;i<4;i++) { next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; next.step=now.step+1; next.key=now.key; if(next.x<1||next.x>n||next.y<1||next.y>m||g[next.x][next.y]=='#')continue;//如果越界 if(g[next.x][next.y]>='A'&&g[next.x][next.y]<='Z'&&g[next.x][next.y]!='X') { for(int j=0;j<4;j++) if(g[next.x][next.y]==up[j]) { if(next.key&(1<<j)&&!vis[next.x][next.y][next.key])//如果没有访问过且拥有此锁的钥匙 { vis[next.x][next.y][next.key]=true; q.push(next); } break; } } else if(g[next.x][next.y]>='a'&&g[next.x][next.y]<='z') { for(int j=0;j<4;j++) if(g[next.x][next.y]==low[j]) { if((next.key&(1<<j))==0)//如果没有此钥匙 next.key+=(1<<j); if(!vis[next.x][next.y][next.key]) { vis[next.x][next.y][next.key]=true; q.push(next); } } } else { if(!vis[next.x][next.y][next.key]) { vis[next.x][next.y][next.key]=true; q.push(next); } } } } return -1; } int main() { while(scanf("%d%d",&n,&m),n|m) { memset(vis,false,sizeof(vis)); for(int i=1;i<=n;i++) { scanf("%s",g[i]+1); for(int j=1;j<=m;j++) if(g[i][j]=='*'){s=i;t=j;} } int ans=bfs(); if(ans==-1)printf("The poor student is trapped!\n"); else printf("Escape possible in %d steps.\n",ans); } return 0; }
HDU 1885 Key Task 状态压缩+搜索,布布扣,bubuko.com
原文:http://blog.csdn.net/crescent__moon/article/details/38502715