http://acm.hust.edu.cn/vjudge/contest/view.action?cid=65959#problem/J
发个题目链接吧,文章复制不成功,就是给一个二维图,# . F J ,# 表示墙,.表示路,F表示火,J表示人,二者都是每次移动一格,(上下左右),F可能会有多个,问人是否可以走出来,只要走到边就算走出来了,
解决,bfs搜索,队列实现,先让火走,再让人走,队列先进先出,看代码
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
const int maxn=1010;
int dx[4]= {0,1,-1,0};
int dy[4]= {1,0,0,-1};
char str[maxn][maxn];
int c,r;
int jx,jy,fx,fy;
struct point
{
int xx,yy,t;
bool isf;
};
queue<point>que;
bool vis[maxn][maxn];
int bfs()
{
while(!que.empty())
{
point now=que.front();
que.pop();
int nx,ny;
///判断是否走出困境
if(!now.isf)
{
if(now.xx==0||now.yy==0||now.xx==c-1||now.yy==r-1)
return now.t;
}
/// 四个方向走一走
for(int i=0; i<4; i++)
{
nx=dx[i]+now.xx;
ny=dy[i]+now.yy;
if(nx>=0&&nx<c&&ny>=0&&ny<r&&!vis[nx][ny])
{
vis[nx][ny]=true;
point tmp;
tmp.xx=nx;
tmp.yy=ny;
if(now.isf)
tmp.t=now.t;
else
tmp.t=now.t+1;
tmp.isf=now.isf;
que.push(tmp);
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
scanf("%d%d",&c,&r);
while(!que.empty())
que.pop();
point h,F;
memset(vis,true,sizeof(vis));///状态
for(int i=0; i<c; i++)
{
scanf("%s",str[i]);
for(int j=0; j<r; j++)
{
if(str[i][j]=='.')
vis[i][j]=false;
if(str[i][j]=='J')
{
h.xx=i;
h.yy=j;
h.t=0;
h.isf=false;
}
if(str[i][j]=='F')
{
F.xx=i;
F.yy=j;
F.t=0;
F.isf=true;
que.push(F);///将所有火坐标加入队列
}
}
}
//que.push(F);
que.push(h);///最后加入人
int ans=bfs();
if(ans==-1)
printf("IMPOSSIBLE\n");
else
printf("%d\n",ans+1);
}
return 0;
}