https://vjudge.net/problem/UVA-11624
UVa真的好卡,,
先预处理‘F’,地图上标记好每个位置火最早出现的时间,之后正常的跑bfs就行了,还是挺水的题
做题前不要莽,磨刀不误砍柴工,仔细想想再下手
最后一道简单搜索了啊,去刷进阶版!
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
int n, m;
char a[1005][1005];
int vis[1005][1005];
int fire[1005][1005];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct node
{
int x, y, t;
};
queue<node> q;
void bfs()
{
node h, next;
while(! q.empty())
{
h = q.front();
q.pop();
for(int i = 0; i < 4; i ++)
{
int u = h.x + dir[i][0];
int v = h.y + dir[i][1];
if(u >= 1 && u <= n && v >= 1 && v <= m && a[u][v] != '#' && ! vis[u][v])
{
vis[u][v] = 1;
next.x = u, next.y = v;
next.t = h.t + 1;
q.push(next);
fire[u][v] = min(next.t, fire[u][v]);
}
}
}
}
int bfs1(int x, int y)
{
queue<node> q;
node h, next;
h.x = x, h.y = y, h.t = 0;
vis[x][y] = 0;
q.push(h);
while(! q.empty())
{
h = q.front();
q.pop();
for(int i = 0; i < 4; i ++)
{
int u = h.x + dir[i][0];
int v = h.y + dir[i][1];
if(u >= 1 && u <= n && v >= 1 && v <= m && a[u][v] != '#' && (fire[u][v] == inf || fire[u][v] > h.t + 1) && vis[u][v] == -1)
{
next.x = u, next.y = v;
next.t = h.t + 1;
q.push(next);
vis[u][v] = next.t;
if((u == 1) || (u == n) || (v == 1) || (v == m))
{
return next.t + 1;
}
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d", &t);
while(t --)
{
while(! q.empty()) q.pop();
node h;
scanf("%d%d", &n, &m);
int jx, jy;
for(int i = 1; i <= n; i ++)
{
scanf("%s", a[i] + 1);
}
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
{
if(a[i][j] == 'F')
{
h.x = i, h.y = j, h.t = 0;
q.push(h);
fire[i][j] = 0;
vis[i][j] = 1;
}
if(a[i][j] == 'J')
{
jx = i;
jy = j;
}
}
memset(vis, 0, sizeof(vis));
memset(fire, 0x3f, sizeof(fire));
bfs();
memset(vis, -1, sizeof(vis));
if(jx == 1 || jx == n || jy == 1 || jy == m)
{
printf("1\n");
continue;
}
int ans = bfs1(jx, jy);
if(ans == -1) printf("IMPOSSIBLE\n");
else printf("%d\n", ans);
}
return 0;
}