1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #include<bits/stdc++.h> using namespace std; int n,m,t,sx,sy,ex,ey; int door[25][25],key[25][25]; bool map[25][25],vis[25][25][1024]; const int dx[]={1,0,-1,0}; const int dy[]={0,1,0,-1}; struct node { int x,y,stat,time; }; bool judgedoor(int x,int y,int stat) { if (door[x][y]==0) return true; if ((stat&(1 << door[x][y]-1))==0) return false; else return true; } bool judge(int x,int y,int stat) { if (judgedoor(x,y,stat) && !vis[x][y][stat]) return true; return false; } int bfs() { queue q; while (!q.empty()) q.pop(); node now,next; now.x=sx;now.y=sy; now.time=0;now.stat=0; q.push(now); vis[sx][sy][0]=true; while (!q.empty()) { now=q.front(); q.pop(); if (now.time==t) return -1; if (now.x==ex && now.y==ey) return now.time; for (int i=0;i<4;i++) { next.x=now.x+dx[i]; next.y=now.y+dy[i]; next.time=now.time+1; next.stat=now.stat; if (next.x>=1 && next.x<=n && next.y>=1 && next.y<=m && map[next.x][next.y]) { if (key[next.x][next.y]!=0) { next.stat=next.stat|(1 << key[next.x][next.y]-1); vis[next.x][next.y][next.stat]=true; q.push(next); } else if (judge(next.x,next.y,next.stat)) { vis[next.x][next.y][next.stat]=true; q.push(next); } } } } return -1; } int main() { while (scanf("%d%d%d",&n,&m,&t)!=EOF) { char ch; memset(map,0,sizeof(map)); memset(door,0,sizeof(door)); memset(key,0,sizeof(key)); memset(vis,0,sizeof(vis)); for (int i=1;i<=n;i++) { ch=getchar(); for (int j=1;j<=m;j++) { ch=getchar(); if (ch!='*') map[i][j]=true; if (ch=='@') sx=i,sy=j; if (ch=='^') ex=i,ey=j; if (ch>='A' && ch<='J') door[i][j]=ch-'A'+1; if (ch>='a' && ch<='j') key[i][j]=ch-'a'+1; } } int ans=bfs(); printf("%d\n",ans); } return 0; }
|