Gym ~ 100625J ~ Jailbreak (0-1 BFS)

题意

有两个犯人要逃出监狱,监狱中有很多门,打开一道门需要花费1的体力,当一个犯人打开门后另一个就不需要在打开了。走到地图外就算逃出监狱了。‘*’表示墙,‘.’表示路(不花体力),‘#’表示门(花费1体力),问两个人都逃出去的最小花费,保证有解。

 

思路

先把地图加一圈‘.’ ,可以把这个问题转化为3个人碰面的问题,两个犯人,一个虚拟的犯人在加的那一圈点的任意一个位置,那么就和Codeforces ~ 590C ~ Three States (0-1 BFS)一样了。枚举碰面地点,求一个最小值即可。

记得每次d数组的清空和MAP的初始化。

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
int n, m, d[5][MAXN][MAXN];
char MAP[MAXN][MAXN];
struct Node
{
    int x, y;
    Node() {}
    Node(int x, int y) : x(x), y(y) {}
};
void BFS(int id, int sx, int sy)
{
    deque<Node> Q;
    d[id][sx][sy] = 0;
    Q.push_back(Node(sx, sy));
    while (!Q.empty())
    {
        Node u = Q.front();
        Q.pop_front();
        for (int i = 0; i < 4; i++)
        {
            int xx = u.x + dx[i], yy = u.y + dy[i];
            if (xx < 0 || yy < 0 || xx > n + 1 || yy > m + 1 || MAP[xx][yy] == '*')
                continue;
            int flag = (MAP[xx][yy] == '#');
            if (d[id][xx][yy] > d[id][u.x][u.y] + flag)
            {
                d[id][xx][yy] = d[id][u.x][u.y] + flag;
                flag ? Q.push_back(Node(xx, yy)) : Q.push_front(Node(xx, yy));
            }
        }
    }
}
int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
        memset(MAP, '.', sizeof(MAP));
        scanf("%d%d", &n, &m);
        int id = 0;
        Node st[3];
        st[id++] = Node(0, 0);
        for (int i = 1; i <= n; i++)
        {
            scanf("%s", MAP[i] + 1);
            for (int j = 1; j <= m; j++)
            {
                if (MAP[i][j] == '$')
                    st[id++] = Node(i, j);
            }
        }
        memset(d, INF, sizeof(d));
        for (int i = 0; i < id; i++)
            BFS(i, st[i].x, st[i].y);
        int ans = INF;
        for (int i = 0; i <= n + 1; i++)
        {
            for (int j = 0; j <= m + 1; j++)
            {
                if (d[0][i][j] == INF || d[1][i][j] == INF || d[2][i][j] == INF)
                    continue;
                if (MAP[i][j] == '#')
                    ans = min(ans, d[0][i][j] + d[1][i][j] + d[2][i][j] - 2);
                else
                    ans = min(ans, d[0][i][j] + d[1][i][j] + d[2][i][j]);
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}
/*
3
5 9
****#****
*..#.#..*
****.****
*$#.#.#$*
*********
5 11
*#*********
*$*...*...*
*$*.*.*.*.*
*...*...*.*
*********.*
9 9
*#**#**#*
*#**#**#*
*#**#**#*
*#**.**#*
*#*#.#*#*
*$##*##$*
*#*****#*
*.#.#.#.*
*********
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值