搜索专题
这题调了一下午+一晚上,多亏大佬相助
很好的题,运用状态压缩的bfs
这道题与以往的迷宫题不同,这道题有门和钥匙还有颜色。所以就要用到状态压缩.
讲的很好的状压
还有要注意 位运算符的优先级很低,甚至比==还低 。 —-大佬原话
source:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define rg register
char a[22][22];
bool b[22][22][1600];
int n,m,t,bx,by,ex,ey;
struct node{int x,y,step,key;};
const int m1[]={1,-1,0,0},m2[]={0,0,1,-1};
queue <node> que;
inline int in(int x,int y,int z){return y<=x&&x<=z;}
int main(){
while(~scanf("%d%d%d",&n,&m,&t)){
while(!que.empty())que.pop();
memset(b,0,sizeof(b));
for(rg int i=1;i<=n;i++){
scanf("%s",a[i]+1);
for(rg int j=1;j<=m;j++)
if(a[i][j]=='@')bx=i,by=j;
}
node k;
k.x=bx; k.y=by; k.key=0; k.step=0;
que.push(k);
while(!que.empty()){
node now=que.front();
que.pop();
int x=now.x,y=now.y;
if(b[x][y][now.key])continue;
b[x][y][now.key]=1;
if(now.step>=t){puts("-1");goto out;}
if(a[x][y]=='^'){printf("%d\n",now.step);goto out;}
for(rg int i=0;i<4;i++)
{
node nex;
nex.x=x+m1[i];
nex.y=y+m2[i];
nex.step = now.step + 1;
nex.key = now.key;
int nx=nex.x,ny=nex.y;
if(!in(nx,1,n)||!in(ny,1,m)||a[nx][ny]=='*') continue;
if(in(a[nx][ny],'A','J')&&((1<<(a[nx][ny]-'A'))&now.key)==0)continue;
if(in(a[nx][ny],'a','j')){
int degit=a[nx][ny]-'a';
nex.key|=(1<<degit);
}
que.push(nex);
}
}puts("-1");
out : "Orz";
}
return 0;
}