Fire!
题目链接https://cn.vjudge.net/problem/UVA-11624
题意:J是人,只有一个,F是火可以有多个,#是墙,‘.’是人和火都能走的地方,问人走出边界需要几步
思路:bfs(好久不写搜索了,手好生。。。),之前被卡住是在判断人和墙同时到达该怎么判断,很明显,同时到达一个地方是不行的,我之前是先让J入队列,不是很好判断,后来先让F入队,那么F能到的地方,J不能过去,即可有效避免这样的情况。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<utility>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#define maxn 1005
#define INF 0x3f3f3f3f
#define LL long long
#define ULL unsigned long long
#define E 1e-8
#define mod 1000000007
#define P pair<int,int>
#define MID(l,r) (l+(r-l)/2)
#define lson(o) (o<<1)
#define rson(o) (o<<1|1)
using namespace std;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char maze[maxn][maxn];
int n,m;
struct node{
int x,y;
int step; //记录人走的步数
int flag; //f=1:人,f=0:火
}p;
queue<node> q;
int bfs()
{
int sum = 1; //最开始有一个人在队列里
while(!q.empty()){
if(sum==0) break; //当队列里没有人了,人一定出不去了,就停止即可
node u = q.front();
q.pop();
if(u.flag==0){
for(int i=0;i<4;++i){
int nx = u.x + dir[i][0];
int ny = u.y + dir[i][1];
if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&maze[nx][ny]=='.'){
maze[nx][ny] = 'F'; //火在蔓延
node v;
v.x = nx;
v.y = ny;
v.flag = 0;
q.push(v);
}
}
}
if(u.flag==1){
sum--;
if(u.x==1||u.x==n||u.y==1||u.y==m){
return u.step;
}
for(int i=0;i<4;++i){
int nx = u.x + dir[i][0];
int ny = u.y + dir[i][1];
if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&maze[nx][ny]=='.'){
maze[nx][ny] = '#'; //人走过的位置,火过去也没有意义了,直接设定为墙就行
sum++;
node v;
v.x = nx;
v.y = ny;
v.flag = 1;
v.step = u.step+1;
q.push(v);
}
}
}
}
return -1;
}
int main()
{
int T;
cin>>T;
while(T--){
while(!q.empty()) q.pop();
cin>>n>>m;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
cin>>maze[i][j];
if(maze[i][j]=='F'){
p.x = i;
p.y = j;
p.flag = 0; //火
q.push(p);
}
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
if(maze[i][j]=='J'){
p.x = i;
p.y = j;
p.step = 1;
p.flag = 1; //人
q.push(p);
}
}
}
int ans = bfs();
if(ans != -1)
printf("%d\n",ans);
else
printf("IMPOSSIBLE\n");
}
return 0;
}