网上的代码都是一个方法,我的代码也是参照网上的,另外解释了下位运算在这里的作用,详情见代码解释
分析
/*
BFS+状态压缩+位运算技巧
以往的BFS之前走过的路就不走了,这里走过的可能还要走,
通过一个三维的vis数组来记录在不同点在不同钥匙状态下是否走过
如果在该钥匙状态下走过了就不再走了
对于钥匙状态(‘a-j’):没有任何钥匙时为0
拿到钥匙a,钥匙状态为0x00000001
再拿到钥匙b,钥匙状态为0x00000011 (0x00000001 | 0x00000010)
对于门序列:比如碰到门B,生成的门序列 int code = 1<<('B'-'A') = 0x00000010
与钥匙状态进行&运算,结果为0说明没有钥匙,否则就是有对应的钥匙
由于钥匙时10把,所以每个点的钥匙状态有2^10种
*/
#include
#include
#include
using namespace std;
struct Node{
int r;
int c;
int state;
int step;
Node(int a,int b,int c,int d){
r = a; //节点所在行
c = b; //节点所在列
state = c; //用来记录当前所拿到钥匙的状态
step = d; //当前走了多少步
}
};
int n,m,t;
int d[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
char pic[21][21];
int vis[21][21][1025];//最后一维保存的是已捡到的钥匙状态
int bfs(int sx,int sy){
int i;
queue q;
q.push(Node(sy,sx,0,0));
vis[sy][sx][0] = 1; //在初始位置钥匙状态为0时,此状态已访问
while(!q.empty()){
Node now = q.front();
q.pop();
if(now.step >= t){
return -1;
}
if(pic[now.r][now.c] == '^'){
return now.step;
}
for(i = 0; i < 4; i++){//右下左上
Node next = now;
next.r = now.r+d[i][0];
next.c = now.c+d[i][1];
next.step++;
//超过边界或者是墙壁
if(next.r < 0 || next.r >=n || next.c < 0 || next.c >= m || pic[next.r][next.c] == '*'){
continue;
}
//碰到门
if(pic[next.r][next.c] >= 'A' && pic[next.r][next.c] <= 'J'){
int code = 1<<(pic[next.r][next.c]-'A');
//运算符"=="的优先级高于"&"
if((next.state&code) == 0){ //将门序列与钥匙状态序列进行&操作来判断是否捡到了对应的钥匙
continue;
}
}
//碰到钥匙改变钥匙状态
if(pic[next.r][next.c] >= 'a' && pic[next.r][next.c] <= 'z'){
int code = 1<<(pic[next.r][next.c]-'a');//生成钥匙序列
next.state = next.state|code;// "|"运算生成新的钥匙状态
}
//在该钥匙状态下已经走过这一步
if(vis[next.r][next.c][next.state] == 1){
continue;
}
vis[next.r][next.c][next.state] = 1;
q.push(next);
}
}
return -1;
}
int main(){
int i,j,sx,sy;
while(cin>>n>>m>>t){
memset(vis,0,sizeof(vis));
//输入初始游戏地图
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
cin>>pic[i][j];
if(pic[i][j] == '@'){
sx = j;
sy = i;
}
}
}
cout<