题目是十把钥匙,所以可以用状态压缩来表示(不解释),之后就是简单的BFS了,不过貌似有点容易爆内存的样子啊….
#include <iostream>
#include <cmath>
#include <cctype>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <utility>
#define inf (1<<28)
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mid ((l+r)>>1)
using namespace std;
#define maxn 24
struct Node
{
int x, y, t, state;
};
char g[maxn][maxn];
int v[maxn][maxn][1<<10];
int n,m,T;
queue<Node>q;
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
inline int ok(char c)
{
return c - (isupper(c) ? 'A' : 'a');
}
inline int check(int x, int y)
{
return (x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*');
}
int Bfs(int x,int y,int t,int state)
{
Node a,b;
while(!q.empty())q.pop();
a.x=x,a.y=y,a.t=t,a.state=state;
q.push(a);
v[x][y][state]=1;
memset(v,0,sizeof(v));
while(!q.empty())
{
a=q.front();
q.pop();
if(a.t>=T)break;
for(int i=0;i<4;i++)
{
b.x=a.x+dir[i][0];
b.y=a.y+dir[i][1];
b.state=a.state;
b.t=a.t+1;
if(check(b.x,b.y)||v[b.x][b.y][b.state])continue;//越界,已访问
if(isupper(g[b.x][b.y])&&!(b.state&(1<<ok(g[b.x][b.y]))))continue;//没钥匙
if(islower(g[b.x][b.y]))b.state|=1<<ok(g[b.x][b.y]);//状态压缩
if(g[b.x][b.y]=='^')return b.t;
if(!v[b.x][b.y][b.state]){
v[b.x][b.y][b.state]=1;
q.push(b);
}
}
}
return -1;
}
int main()
{
int x=0,y=0;
while(~scanf("%d%d%d",&n,&m,&T)){
T -= 1;
for(int i=0;i<n;i++){
scanf("%s", g[i]);
for(int j=0;j<m;j++){
if(g[i][j]=='@'){
g[i][j]='.';
x=i,y=j;
}
}
}
printf("%d\n", Bfs(x,y,0,0));
}
return 0;
}