跟简单搜索不同的是,这个钥匙开门机制,确实很难去想。后来看到了别人将其转化为二进制数进行存储表示钥匙状态,因为最多10把钥匙,所以只需要2^10就可以存下,而且要注意,因为在取钥匙开门的过程中,可能会走过一个点数次,所以需要将钥匙状态存储并判断是同一状态下,有无重复走过。
if(maps[next.x][next.y] >= 'a' &&maps[next.x][next.y] <= 'j'){
int temp1 = maps[next.x][next.y] - 'a';
//该钥匙之前没拿过
if((next.sta&(1<<temp1)) == 0){
next.sta += (1<<temp1);
}
}
else if(maps[next.x][next.y] >= 'A' &&maps[next.x][next.y] <= 'J'){
int temp2 = maps[next.x][next.y] - 'A';
//到某一个门但是没有钥匙
if((next.sta&(1<<temp2)) == 0){
continue;
}
}
/*获取钥匙状态,利用位运算求某一位表示的钥匙是否已经拿到,
遇到门时判断是否有门钥匙*/
完整代码
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 25;
struct node
{
int x;
int y;
int step;
int sta;
};
char maps[MAXN][MAXN];
int vis[MAXN][MAXN][1030];
int dir[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
int n,m,t;
bool if_fair(int x,int y,int sta)
{
if(x >= 0&&y >= 0&&x < n&&y < m&&maps[x][y] != '*'&&!vis[x][y][sta]){
return true;
}
return false;
}
int bfs(node x)
{
memset(vis,0,sizeof(vis));
queue <node> q;
q.push(x);
vis[x.x][x.y][0] = 1;
node now,next;
while(!q.empty()){
now = q.front();
q.pop();
if(maps[now.x][now.y] == '^'){
if(now.step < t){
return now.step;
}
return -1;
}
for(int i = 0; i < 4; i++){
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
next.step = now.step + 1;
next.sta = now.sta;
if(if_fair(next.x,next.y,next.sta)){
if(maps[next.x][next.y] >= 'a' &&maps[next.x][next.y] <= 'j'){
int temp1 = maps[next.x][next.y] - 'a';
//该钥匙之前没拿过
if((next.sta&(1<<temp1)) == 0){
next.sta += (1<<temp1);
}
}
else if(maps[next.x][next.y] >= 'A' &&maps[next.x][next.y] <= 'J'){
int temp2 = maps[next.x][next.y] - 'A';
//到某一个门但是没有钥匙
if((next.sta&(1<<temp2)) == 0){
continue;
}
}
q.push(next);
vis[next.x][next.y][next.sta] = 1;
}
}
}
return -1;
}
int main()
{
node b;
while(cin>>n>>m>>t){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin>>maps[i][j];
if('@' == maps[i][j]){
b.x = i;
b.y = j;
b.step = 0;
b.sta = 0;
}
}
}
int ans = bfs(b);
cout<<ans<<endl;
}
}
本文介绍了一种解决迷宫寻宝问题的算法,通过将钥匙状态转化为二进制数进行存储,利用位运算判断是否拥有对应钥匙。文章详细解释了如何在遍历迷宫过程中更新钥匙状态,避免重复探索已知路径。

4978

被折叠的 条评论
为什么被折叠?



