您的位置:首页 > 其它

BFS(两点搜索) UVA 11624 Fire!

2015-08-04 21:02 351 查看
题目传送门

 /*
BFS:首先对火搜索,求出火蔓延到某点的时间,再对J搜索,如果走到的地方火已经烧到了就不入队,直到走出边界。
*/
/************************************************
Author        :Running_Time
Created Time  :2015-8-4 8:11:54
File Name     :UVA_11624.cpp
*************************************************/

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <cstdlib>
#include <ctime>
using namespace std;

#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef long long ll;
const int MAXN = 1e3 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
char maze[MAXN][MAXN];
bool vis[MAXN][MAXN];
int step[MAXN][MAXN];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int n, m;

bool judge_f(int x, int y)  {
if (x < 1 || x > n || y < 1 || y > m || vis[x][y] || maze[x][y] == '#')    return false;
return true;
}

bool judge_j(int x, int y)  {
if (x < 1 || x > n || y < 1 || y > m)   return true;
return false;
}

void BFS_F(void)  {
memset (step, INF, sizeof (step));
memset (vis, false, sizeof (vis));
queue<pair<int, int> > Q;
for (int i=1; i<=n; ++i)    {
for (int j=1; j<=m; ++j)    {
if (maze[i][j] == 'F') {
Q.push (make_pair (i, j));  vis[i][j] = true;
step[i][j] = 0;
}
}
}
while (!Q.empty ()) {
int x = Q.front ().first, y = Q.front ().second;    Q.pop ();
for (int i=0; i<4; ++i) {
int tx = x + dx[i], ty = y + dy[i];
if (!judge_f (tx, ty))    continue;
step[tx][ty] = step[x][y] + 1;
Q.push (make_pair (tx, ty));    vis[tx][ty] = true;
}
}
}

void BFS_J(void)    {
memset (vis, false, sizeof (vis));
queue<pair<int, int> > Q;
for (int i=1; i<=n; ++i)    {
for (int j=1; j<=m; ++j)    {
if (maze[i][j] == 'J')  {
Q.push (make_pair (i, j)); step[i][j] = 0; vis[i][j] = true;   break;
}
}
}
while (!Q.empty ()) {
int x = Q.front ().first, y = Q.front ().second;    Q.pop ();
for (int i=0; i<4; ++i) {
int tx = x + dx[i], ty = y + dy[i];
if (judge_j (tx, ty))    {
printf ("%d\n", step[x][y] + 1);    return ;
}
if (step[x][y] + 1 >= step[tx][ty] || vis[tx][ty] || maze[tx][ty] == '#') continue;
Q.push (make_pair (tx, ty));    step[tx][ty] = step[x][y] + 1;  vis[tx][ty] = true;
}
}
puts ("IMPOSSIBLE");
}

int main(void)    {     //UVA 11624 Fire!
int T;  scanf ("%d", &T);
while (T--) {
scanf ("%d%d", &n, &m);
for (int i=1; i<=n; ++i)    {
scanf ("%s", maze[i] + 1);
}
BFS_F ();   BFS_J ();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: