FZU2150 Fire Game(搜索题:bfs)

题目

       给一个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());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值