一个BFS加状态压缩的题目。
开一个map[21][21][1030]的数组用来判断是否走到重复的情况,20为图的大小,1024为10把钥匙经过状态压缩后的最大值。
即当走到某一点时,如果手上钥匙的状态和以前重复了,就说明不需要再往下走了。
#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;
struct node{
int x,y,t,f;
};
int n,m,t,MAX;
int value[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
char map[30][30];
bool flag[21][21][1030];
int BFS(int sx,int sy){
queue<node> q;
node temp1,temp2;
temp1.x = sx;
temp1.y = sy;
temp1.t = 0;
temp1.f = 0;
flag[temp1.x][temp1.y][0] = 1;
q.push(temp1);
while(q.empty() != true){
temp1 = q.front();
q.pop();
if(temp1.t>=t-1) continue;
temp2.t = temp1.t+1;
for(int i=0;i<4;i++){
temp2.x = temp1.x + value[i][0];
temp2.y = temp1.y + value[i][1];
temp2.f = temp1.f;
if(temp2.x>=0 && temp2.x<m && temp2.y>=0 && temp2.y<n && map[temp2.y][temp2.x]!='*' && !flag[temp2.y][temp2.x][temp2.f]){
if(map[temp2.y][temp2.x]>='A' && map[temp2.y][temp2.x]<='J' && ((temp2.f & (1<<(map[temp2.y][temp2.x]-'A'))) == 0)) continue;
if(map[temp2.y][temp2.x]>='a' && map[temp2.y][temp2.x]<='j'){
temp2.f = temp2.f | (1<<(map[temp2.y][temp2.x]-'a'));
flag[temp2.y][temp2.x][temp2.f] = 1;
q.push(temp2);
continue;
}
if(map[temp2.y][temp2.x] == '^') return temp2.t;
flag[temp2.y][temp2.x][temp2.f] = 1;
q.push(temp2);
}
}
}
return -1;
}
int main(){
int i,j,sx,sy,SUM,temp;
while(cin>>n>>m>>t){
for(i=0;i<n;i++) scanf("%s",&map[i]);
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(map[i][j] == '@'){
sx = j;
sy = i;
}
}
}
memset(flag,0,sizeof(flag));
printf("%d\n",BFS(sx,sy));
}
return 0;
}