学习到位压缩,位压缩还是很重要的,第一次做位压缩的题目,感觉以前学习C语言位运算的时候,不太扎实啊!
开始的时候,dir数组中少加了一个逗号,调试了十多分钟才发现,还是不够仔细……
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
char map[21][21];
int flag[21][21][1205];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
int sx,sy,n,m,t;
struct node
{
int x,y,time,key;
};
void bfs()
{
int i;
node cur,next;
queue<node> q;
cur.x=sx;
cur.y=sy;
cur.time=0;
cur.key=0;
q.push(cur);
while(!q.empty())
{
cur=q.front();
q.pop();
if(map[cur.x][cur.y]=='^')
{
if(cur.time<t) {cout<<cur.time<<endl;return ;}
break;
}
for(i=0;i<4;i++)
{
next.time=cur.time;
next.key=cur.key;
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
if(next.x>=0&&next.x<n&next.y>=0&&next.y<m&&map[next.x][next.y]!='*')
{
next.time+=1;
// cout<<next.time<<endl;
if(map[next.x][next.y]>='A'&&map[next.x][next.y]<='J')
{
int key1=map[next.x][next.y]-'A';
if(((next.key>>key1)&1)&&!flag[next.x][next.y][next.key]) //手中是否有开此门的钥匙
{
// cout<<"ok1"<<endl;
flag[next.x][next.y][next.key]=1;
q.push(next);
}
}
else if(map[next.x][next.y]>='a'&&map[next.x][next.y]<='j')
{
int key1=(1<<(map[next.x][next.y]-'a')); //因为0000是0001
next.key|=key1; //取钥匙
if(!flag[next.x][next.y][next.key])
{
// cout<<"ok2"<<endl;
flag[next.x][next.y][next.key]=1;
q.push(next);
}
}
else
{
if(!flag[next.x][next.y][next.key])
{
// cout<<"ok3"<<endl;
flag[next.x][next.y][next.key]=1;
q.push(next);
}
}
}
}
}
cout<<"-1"<<endl;
}
int main()
{
// freopen("in.txt","r",stdin);
int i,j;
while(cin>>n>>m>>t)
{
memset(flag,0,sizeof(flag));
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
cin>>map[i][j];
if(map[i][j]=='@')
{
sx=i;
sy=j;
}
}
}
bfs();
}
return 0;
}