思路:因为存在门和钥匙,所以一个点可能被多次访问,解决方法是在vis数组中保存当前持有的钥匙的状态,对于一个相同的点,一种持有钥匙的状态只能访问一次,很容易理解在没有更多钥匙的情况下,多次访问这个点得到的结果不会更优(因为只有10把钥匙,代码中用二进制储存,但用bool数组储存也是完全可以的。另外用不用优先队列对于这题的影响不大)
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
typedef unsigned int ui;
#define mp(a,b) make_pair(a,b)
#define mem(a,b) memset(a,b,sizeof(a))
#define debug(a) printf("Debug: %d\n",a)
const int Mod = 1000000007;
const int maxn =22;
const int INF = 0x3f3f3f3f;
int n,m,t;
int sx,sy,ex,ey;
char mp[maxn][maxn];
bool vis[maxn][maxn][4];
int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
struct Node
{
int x,y,v;
int key;
Node(){}
Node(int X,int Y,int V,int K){x=X; y=Y; v=V; key=K;}
bool operator<(const Node& rhs) const{
return v>rhs.v;
}
};
int BFS()
{
priority_queue<Node> qu;
qu.push(Node(sx,sy,0,0));
mem(vis,0);
Node tmp;
int tx,ty,dx,dy;
int keynum,doornum;
while(!qu.empty())
{
tmp=qu.top();
qu.pop();
tx=tmp.x; ty=tmp.y;
if (tmp.v>=t) return -1;
if (tx==ex && ty==ey) return tmp.v;
for (int i=0;i<4;i++)
{
dx=tx+dir[i][0];
dy=ty+dir[i][1];
if (dx>=0 && dx<n && dy>=0 && dy<m && !vis[dx][dy][i] && mp[dx][dy]!='*')
{
vis[dx][dy][i]=1;
char C=mp[dx][dy];
if (C>='A' && C<='J')
{
doornum=C-'A';
if ((tmp.key>>doornum)==0) continue;
else qu.push(Node(dx,dy,tmp.v+1,tmp.key));
}
else if (C>='a' && C<='j')
{
keynum=C-'a';
qu.push(Node(dx,dy,tmp.v+1,tmp.key | (1<<keynum)));
}
}
}
}
return -1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
while(cin>>n>>m>>t)
{
char c;
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
{
cin>>c;
mp[i][j]=c;
if (c=='@') sx=i,sy=j;
else if (c=='^') ex=i,ey=j;
}
cout<<BFS()<<'\n';
}
}