题目大意:
就是给你两个数n和m,然后有n行m列,map[i][j];
一个平面迷宫中有一个人,迷宫中有些点起火了,火和人每个单位时间只能向相邻的格子移动,
其中有一些空间被墙壁占据,问这个人在不被火烧到的情况下,离开迷宫的最快时间。
解题思路:
就是一个简单的bfs广搜,最短路问题基本上都用bfs
/*
2015 - 09 - 14 晚上
Author: ITAK
Motto:
今日的我要超越昨日的我,明日的我要胜过今日的我,
以创作出更好的代码为目标,不断地超越自己。
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 1e3+5;
const double eps = 1e-7;
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
struct node
{
int x, y, flag, step;///flag:标记,step:步数
};
int m, n;
char map[maxn][maxn];
bool vis[maxn][maxn];///是否被访问过
queue<node>q;///队列
int bfs()
{
while(!q.empty())
{
node start, end;///一个开始时候和结束时候的
start = q.front();///访问对首元素
q.pop();///推出
end = start;
///推出条件
if((start.x==0||start.y==0||start.x==n-1||start.y==m-1) && start.flag)
return start.step;
///一下是计算情况
for(int i=0; i<4; i++)
{
end.x = start.x + dir[i][0];
end.y = start.y + dir[i][1];
end.flag = start.flag;
end.step = start.step+1;
if(end.x<0 || end.x>n-1 || end.y<0 || end.y>m-1)
continue;
if(!vis[end.x][end.y] && map[end.x][end.y]=='.' && (end.x>=0&&end.x<n)
&& (end.y>=0&&end.y<m))
{
vis[end.x][end.y] = true;
q.push(end);
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
while(!q.empty())
q.pop();
memset(vis, false, sizeof(vis));
node start, end;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin>>map[i][j];
///分别记录J和F的位置
if(map[i][j] == 'J')
{
start.x = i;
start.y = j;
start.flag = true;
start.step = 1;
vis[start.x][start.y] = true;
}
if(map[i][j] == 'F')
{
end.x = i;
end.y = j;
end.flag = false;
end.step = 1;
vis[end.x][end.y] = 1;
q.push(end);
}
}
}
q.push(start);
int ret = bfs();
if(!ret)
puts("IMPOSSIBLE");
else
cout<<ret<<endl;
}
return 0;
}
/*
南山南 (Live) - 张磊
词:马頔
曲:马頔
你在南方的艳阳里大雪纷飞
我在北方的寒夜里四季如春
如果天黑之前来得及
我要忘了你的眼睛
穷极一生 做不完一场梦
他不再和谁谈论相逢的孤岛
因为心里早已荒无人烟
他的心里再装不下一个家
做一个只对自己说谎的哑巴
他说你任何为人称道的美丽
不及他第一次遇见你
时光苟延残喘 无可奈何
如果所有土地连在一起
走上一生 只为拥抱你
喝醉了他的梦 晚安
你在南方的艳阳里大雪纷飞
我在北方的寒夜里四季如春
如果天黑之前来得及
我要忘了你的眼睛
穷极一生 做不完一场梦
大梦初醒 荒唐了一生
南山南 北秋悲
南山有谷堆
南风喃 北海北
北海有墓碑
南山南 北秋悲
南山有谷堆
南风喃 北秋悲
北海有墓碑
北海有墓碑
*/