您的位置:首页 > 其它

百练 4116 拯救行动

2016-07-21 09:47 281 查看
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=200+5;
char p[maxn][maxn];
int n,m,xm,ym,xw,yw;
int vis[maxn][maxn];
struct node{
int l,x,y;
int steps;
node(int l,int x,int y,int steps) : l(l),x(x),y(y),steps(steps) {};
};
void BFS()
{
vis[xm][ym]=1;
queue<node> q;
while(!q.empty()) q.pop();
q.push(node(1,xm,ym,0));
while(!q.empty())
{
node ans=q.front();
q.pop();
int x=ans.x,y=ans.y,steps=ans.steps;
if(ans.x==xw&&ans.y==yw) {printf("%d\n",steps);return ;}
if(ans.l==0){
q.push(node(1,x,y,steps+1));
}
else{
if(x>1&&!vis[x-1][y]){
vis[x-1][y]=1;
if(p[x-1][y]=='@'||p[x-1][y]=='a') q.push(node(1,x-1,y,steps+1));
else if(p[x-1][y]=='x') q.push(node(0,x-1,y,steps+1));
}
if(y>1&&!vis[x][y-1]){
vis[x][y-1]=1;
if(p[x][y-1]=='@'||p[x][y-1]=='a') q.push(node(1,x,y-1,steps+1));
else if(p[x][y-1]=='x') q.push(node(0,x,y-1,steps+1));
}
if(x<n&&!vis[x+1][y]){
vis[x+1][y]=1;
if(p[x+1][y]=='@'||p[x+1][y]=='a') q.push(node(1,x+1,y,steps+1));
else if(p[x+1][y]=='x') q.push(node(0,x+1,y,steps+1));
}
if(y<m&&!vis[x][y+1]){
vis[x][y+1]=1;
if(p[x][y+1]=='@'||p[x][y+1]=='a') q.push(node(1,x,y+1,steps+1));
else if(p[x][y+1]=='x') q.push(node(0,x,y+1,steps+1));
}
}
}
printf("Impossible\n");
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
memset(p,0,sizeof(p));
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>p[i][j];
if(p[i][j]=='r') xm=i,ym=j;
if(p[i][j]=='a') xw=i,yw=j;
}
}
BFS();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: