您的位置:首页 > 其它

UVA - 11624 Fire!(15.10.10 搜索专题)bfs

2015-10-11 22:41 483 查看
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=28833

题意:joe在图中,图中有几个起火点,火以没分钟每格的速度蔓延,Joe的移动速度也是每分钟每格,问Joe有没有可能从火场逃生,跑出图。

思路:先对每个起火点bfs,求出图中各个点起火的时间(最早的时间),然后在对Joe来bfs,注意已经起火的地方是不能走的。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<climits>
using namespace std;

#define inf 0x3f3f3f

const int dirx[4] = { 0, 0, 1, -1 };
const int diry[4] = { 1, -1, 0, 0 };

char map[1010][1010];
bool vis[1010][1010];

int disFire[1010][1010];
int disPeo[1010][1010];

int r, c;

struct Point
{
int x, y;
Point(int xx, int yy) :x(xx), y(yy){}
Point(){}
};

Point posFire[100010];
int numOfFire;

Point posJoe;

void bfsFire(int x,int y)
{
queue<Point>que;
que.push(Point(x, y));
disFire[x][y] = 0;
while (!que.empty())
{
Point loc = que.front();
que.pop();
for (int i = 0; i < 4; i++)
{
int xx = loc.x + dirx[i];
int yy = loc.y + diry[i];
if (xx >= 0 && xx < r && yy >= 0 && yy<c && map[xx][yy] == '.'&& disFire[xx][yy]>disFire[loc.x][loc.y] + 1)
{
que.push(Point(xx, yy));
disFire[xx][yy] = disFire[loc.x][loc.y] + 1;
}
}
}
}

int bfsPeo(int x, int y)
{
queue<Point>que;
que.push(Point(x, y));
disPeo[x][y] = 0;
vis[x][y] = true;
while (!que.empty())
{
Point loc = que.front();
que.pop();

if (loc.x == 0 || loc.y == 0 || loc.x == r - 1 || loc.y == c - 1)
return disPeo[loc.x][loc.y]+1;

for (int i = 0; i < 4; i++)
{
int xx = loc.x + dirx[i];
int yy = loc.y + diry[i];
if (xx >= 0 && xx < r && yy >= 0 && yy<c && map[xx][yy] == '.'&& disFire[xx][yy]>disPeo[loc.x][loc.y]+1 && !vis[xx][yy])
{
que.push(Point(xx, yy));
disPeo[xx][yy] = disPeo[loc.x][loc.y] + 1;
vis[xx][yy] = true;
}
}
}
return -1;
}

int main()
{
int casen;
cin >> casen;
while (casen--)
{
cin >> r >> c;
for (int i = 0; i < r; i++)
cin >> map[i];

numOfFire = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
{
if (map[i][j] == 'F')
{
posFire[numOfFire].x = i;
posFire[numOfFire++].y = j;
}
else if (map[i][j] == 'J')
{
posJoe.x = i;
posJoe.y = j;
}
}

memset(disFire, inf, sizeof(disFire));
memset(disPeo, inf, sizeof(disPeo));
memset(vis, false, sizeof(vis));

for (int i = 0; i < numOfFire; i++)
{
int x = posFire[i].x;
int y = posFire[i].y;
bfsFire(x, y);
}

int ans = bfsPeo(posJoe.x, posJoe.y);

if (ans == -1) cout << "IMPOSSIBLE" << endl;
else cout << ans << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm 搜索 bfs