思路:
有点像我们以前玩的魔塔,拿小写字母表示钥匙,去开大写字母的门,如果用模板的bfs去写,将vis设为二维数组,记录地图上的二维坐标,来标记走过的点,那么这样很明显会失败,因为勇士是可能要拿钥匙后,走之前标记过的回头路,所以我们要用vis三维数组存状态。第三维存钥匙的种类。
那么问题来了,钥匙是个字符,而vis是三维整型数组,怎么转化呢?
可以用二进制的按位与,按位或操作来实现钥匙的获取,与门的解码。
'<<'是左移运算符,将钥匙所代表的a~j用0~9来表示,将其左移后与之前的k按位或,可以得到1111111一串代码,其中第i位的1代表第i个钥匙。
nexxt.k=temp.k;
nexxt.k=temp.k|(1<<(s[nextt.x][nextt.y]-'a'));
已知temp.k代表目前有的钥匙串代码,与现在碰到的门的串代码按位与,如果返回结果大于0,则说明目前有能开此门的钥匙,若为0,则说明没有该钥匙。
kk=temp.k&(1<<s[nextt.x][nextt.y]-'A');
#include <iostream>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=25;
const int INF=0x3f3f3f3f;
int n,m,t;
int sx,sy,ex,ey;
char s[maxn][maxn];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int vis[maxn][maxn][2000];
struct Node
{
int x,y,step;
int k;
};
Node now,temp,nextt;
queue<Node>q;
void bfs()
{
now.x=sx;now.y=sy;now.step=0;now.k=0;
vis[now.x][now.y][now.k]=1;
q.push(now);
while(!q.empty())
{
temp=q.front();
q.pop();
if(temp.step>=t)
{
cout<<"-1"<<endl;
return ;
}
if(temp.x==ex&&temp.y==ey)
{
cout<<temp.step<<endl;
return ;
}
for(int i=0;i<4;i++)
{
nextt.x=temp.x+dx[i];
nextt.y=temp.y+dy[i];
if(nextt.x>=1&&nextt.x<=n&&nextt.y>=1&&nextt.y<=m&&s[nextt.x][nextt.y]!='*')
{
nextt.step=temp.step+1;
nextt.k=temp.k;
if(s[nextt.x][nextt.y]>='a'&&s[nextt.x][nextt.y]<='z')
{
nextt.k=temp.k|(1<<(s[nextt.x][nextt.y]-'a'));
if(vis[nextt.x][nextt.y][nextt.k]==0)
{
vis[nextt.x][nextt.y][nextt.k]=1;
q.push(nextt);
}
}
else if(s[nextt.x][nextt.y]>='A'&&s[nextt.x][nextt.y]<='Z')
{
int kk=temp.k&(1<<(s[nextt.x][nextt.y]-'A'));
if(vis[nextt.x][nextt.y][temp.k]==0&&kk)
{
vis[nextt.x][nextt.y][temp.k]=1;
q.push(nextt);
}
}
else
{
if(vis[nextt.x][nextt.y][nextt.k]==0)
{
vis[nextt.x][nextt.y][nextt.k]=1;
q.push(nextt);
}
}
}
}
}
cout<<"-1"<<endl;
}
int main()
{
while(cin>>n>>m>>t)
{
while(!q.empty())
q.pop();
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>s[i][j];
if(s[i][j]=='@')
{
sx=i;sy=j;
}
if(s[i][j]=='^')
{
ex=i;ey=j;
}
}
}
bfs();
}
return 0;
}