您的位置:首页 > 其它

uva 11624 Fire

2015-09-14 18:29 274 查看
题目大意:

一个平面迷宫中有一个人,迷宫中有些点起火了,火和人每个单位时间只能向相邻的格子移动,其中有一些空间被墙壁占据,问这个人在不背或烧到的情况下,离开迷宫的最快时间。

大部分人用两个bfs,我觉得一个就行,先把起火点压入队列(起火点可能有多个),最后把人压入队列,bfs即可,第一道没看别人博客写的- -;

ps:由于dir数组初始化赋值弄错了,以至于看了两天,怎么看都觉得挺对的,服了。。。

代码:

#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
struct node
{
int x,y,step,flag;
};
int  dir[4][2] = {1,0,-1,0,0,1,0,-1};
char map[1005][1005];
int vis[1005][1005];
int n,m;
queue<node>q;
int bfs()
{

//q.push(s);
//q.push(e);
//[s.x][s.y]=1;
// /is[s.x][s.y]=1;
while(!q.empty())
{     node s,e;
s=q.front();
q.pop();
e=s;
//if(s.x<0||s.x>=n||s.y<0||s.y>=m) continue;
if((s.x==0||s.y==0||s.x==n-1||s.y==m-1)&&s.flag)
return s.step;
for(int i=0;i<4;i++)
{
e.x=s.x+dir[i][0];
e.y=s.y+dir[i][1];
e.step=s.step+1;
e.flag=s.flag;
if(e.x<0||e.x>=n||e.y<0||e.y>=m) continue;
if(!vis[e.x][e.y]&&map[e.x][e.y]=='.'&&e.x>=0&&e.x<n&&e.y>=0&&e.y<m)
{
vis[e.x][e.y]=1;
q.push(e);
}
}
}
return 0;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
while(!q.empty()) q.pop();
memset(vis,0,sizeof(vis));
node s;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>map[i][j];
if(map[i][j]=='J')
{
s.x=i;
s.y=j;
s.flag=1;
s.step=1;
vis[s.x][s.y]=1;
//q.push(s);
}
if(map[i][j]=='F')
{
node e;
e.x=i;
e.y=j;
e.flag=0;
e.step=1;
vis[e.x][e.y]=1;
q.push(e);
}
}
}
q.push(s);
int ans=bfs();
if(ans==0) cout<<"IMPOSSIBLE"<<endl;
else cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: