/* 记录状态的bfs,用到了二进制状态压缩 http://acm.hdu.edu.cn/showproblem.php?pid=1429 */ #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include<queue> #define N 20010 using namespace std; struct State { int x,y,key,step; State(int x1,int y1,int key1,int step1) { x=x1,y=y1,key=key1,step=step1; } }; int n,m,les,sx,sy,vis[21][21][1025]; char map[21][21]; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; inline bool check(State T) { if(T.x>0&&T.y>0&&T.x<=n&&T.y<=m&&map[T.x][T.y]!='*'&&T.step<les) return true; return false; } int bfs() { queue<State> q; memset(vis,0,sizeof(vis)); q.push(State(sx,sy,0,0)); vis[sx][sy][0]=1; while(q.size()) { State src=q.front();q.pop(); for(int j=0;j<4;j++) { State cur=State(src.x+dx[j],cur.y=src.y+dy[j],cur.key=src.key,cur.step=src.step+1); if(check(cur)&&!vis[cur.x][cur.y][cur.key]) { vis[cur.x][cur.y][cur.key]=1; if(map[cur.x][cur.y]=='^')return cur.step; else if(map[cur.x][cur.y]=='.') q.push(cur); else if(map[cur.x][cur.y]>='a'&&map[cur.x][cur.y]<='j') { cur.key=cur.key|(1<<(map[cur.x][cur.y]-'a')); q.push(cur); } else if(map[cur.x][cur.y]>='A'&&map[cur.x][cur.y]<='J'&&(cur.key&(1<<(map[cur.x][cur.y]-'A')))) { q.push(cur); } } } } return -1; } int main() { while(scanf("%d%d%d",&n,&m,&les)!=EOF) { getchar(); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { map[i][j]=getchar(); if(map[i][j]=='@') { sx=i,sy=j; map[i][j]='.'; } } getchar(); } cout<<bfs()<<endl; getchar(); } }