FZU2150 Fire Game(搜索题:bfs)

来源:互联网 发布:网络彩票2018重启时间 编辑:程序博客网 时间:2024/04/16 13:08

题目

       给一个n*m的网格,只有草’#’和空地’.’,初始可以在两个地方放火,来烧草,火每回合向上下左右蔓延。问如何放置,使得最少的回合内能烧完所有的草,输出回合数,如果无解输出‘-1’。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

分析

       参考y761823 的解答。我选拔赛出的“代号2”跟这题有点类似。

       注意其规模很小,可以暴力求解。即暴力初始放火的两个位置。然后用bfs模拟烧的过程:用一个dis矩阵记录每个有草的地方被烧到的回合数,有草的地方dis都初始为INF。bfs模拟结束后,返回dis矩阵有草的地方中值最大的即可。

#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <queue>using namespace std;typedef long long LL;#define REP(i, n)  for(int i = 1; i <= n; ++i)const int MAXN = 13;const int INF = 0x3f3f3f3f;char mat[MAXN][MAXN];int dis[MAXN][MAXN];int n, m, T;struct Node {    int x, y;    Node() {}     Node(int x, int y): x(x), y(y) {}};queue<Node> que;int fx[] = {-1, 0, 1, 0};int fy[] = {0, 1, 0, -1};int bfs (int x1, int y1, int x2, int y2) {    // 只需要考虑两个起始点都烧到草的情况    if(mat[x1][y1] == '.' || mat[x2][y2] == '.') return INF;    memset(dis, 0x3f , sizeof(dis));    dis[x1][y1] = dis[x2][y2] = 0;    que.push(Node(x1, y1));    que.push(Node(x2, y2));    while(!que.empty()) {        Node now = que.front(); que.pop();        for(int i = 0; i < 4; ++i) {            int nx = now.x + fx[i], ny = now.y + fy[i];            if(mat[nx][ny] == '#' && dis[nx][ny] == INF) {                dis[nx][ny] = dis[now.x][now.y] + 1;                que.push(Node(nx, ny));            }        }    }    int res = 0;    REP(i, n) REP(j, m) {        if(mat[i][j] == '#') res = max(res, dis[i][j]);    }    return res;}int solve() {    int res = INF;    REP(x1, n) REP(y1, m) REP(x2, n) REP(y2, m) {        res = min(res, bfs(x1, y1, x2, y2));    }    if(res == INF) return -1;    else return res;}int main() {    scanf("%d", &T);    REP(t, T) {        scanf("%d%d", &n, &m);        memset(mat, '.', sizeof(mat));        for(int i = 1; i <= n; ++i)            scanf("%s", &mat[i][1]);        printf("Case %d: %d\n", t, solve());    }}

0 0
原创粉丝点击