UVA 11624 Fire!(BFS)

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2671

题意:J需要逃出矩阵,只有走到矩阵边即算成功。但是矩阵中存在几个F代表火,火每一秒向四周扩散,问J能否逃出?求最短路径。

思路一:先对火进行搜索,记录火到每个点的最短时间。然后对J进行搜索,J每次到一个点,判断J到这个点的时间是否早于火到达的时间。若早即可走。

思路二:对人和火进行同时搜索,每次搜索先处理火的,再处理人的。判断同思路一。

代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>

using namespace std;

const int INF = 0x3f3f3f3f;
const int N = 1e3 + 10;

struct Node {
  int x, y;
  int step;
};

int r, c;
vector<Node> f;
int fire[N][N];
int dis[N][N];
char _map[N][N];
int x[4] = {0, 1, 0, -1};
int y[4] = {1, 0, -1, 0};

bool safe(Node now) {
  if (now.x == 0 || now.x == r - 1 || now.y == 0 || now.y == c - 1)
    return true;
  return false;
}

int bfs(Node s) {
  queue<Node> q, p;
  for (int i = 0; i < f.size(); i++) {
    p.push(f[i]);
    fire[f[i].x][f[i].y] = 0;
  }
  q.push(s);
  dis[s.x][s.y] = 0;
  while (!q.empty()) {
    int nt = q.front().step; // 记录当前搜索的时间
    while (!p.empty() && p.front().step <= nt) { // 处理当前时间的火
      Node nf = p.front();
      p.pop();
      for (int i = 0; i < 4; i++) {
        Node tf;
        tf.x = nf.x + x[i];
        tf.y = nf.y + y[i];
        tf.step = nf.step + 1;
        if (tf.x >= 0 && tf.x < r && tf.y >= 0 && tf.y < c 
          && _map[tf.x][tf.y] != '#' && fire[tf.x][tf.y] > tf.step) {
          fire[tf.x][tf.y] = tf.step;
          p.push(tf);
        }
      }
    }
    while (!q.empty() && q.front().step <= nt) { // 处理当前时间的人
      Node nj = q.front();
      q.pop();
      if (safe(nj))
        return nj.step;
      for (int i = 0; i < 4; i++) {
        Node tj;
        tj.x = nj.x + x[i];
        tj.y = nj.y + y[i];
        tj.step = nj.step + 1;
        if (tj.x >= 0 && tj.x < r && tj.y >= 0 && tj.y < c
          && _map[tj.x][tj.y] != '#' && dis[tj.x][tj.y] > tj.step
          && fire[tj.x][tj.y] > tj.step) {
          dis[tj.x][tj.y] = tj.step;
          q.push(tj);
        }
      }
    }
  }
  return -1;
}

int main() {
  int t_case;
  scanf("%d", &t_case);
  for (int i_c = 0; i_c < t_case; i_c++) {
    scanf("%d%d", &r, &c);
    for (int i = 0; i < r; i++)
      scanf("%s", _map[i]);
    Node st;
    f.clear();
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (_map[i][j] == 'J') {
          st.x = i, st.y = j, st.step = 0;
        }
        else if (_map[i][j] == 'F') {
          Node t;
          t.x = i, t.y = j, t.step = 0;
          f.push_back(t);
        }
      }
    }
    memset(dis, INF, sizeof(dis));
    memset(fire, INF, sizeof(fire));
    int res = bfs(st);
    if (res == -1)
      printf("IMPOSSIBLE\n");
    else
      printf("%d\n", res + 1);
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值