AOJ0558 广度优先搜索

#include <iostream>
#include <queue>
using namespace std;
typedef pair<int, int> P;
typedef long long ll;
int width, height, count, startH[10], startW[10], endH[10], endW[10], ans[1007][1007], dh[5] = {0, 1, 0, -1, 0}, dw[5] = {0, 0, 1, 0, -1}, inf = 0x3f3f3f3f;
char field[1007][1007], tag[10] = {'S', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
void setStart(int h, int w, char c)
{
    for (int i = 0; i <= count; i++)
    {
        if (c != tag[i])
        {
            continue;
        }
        startH[i] = h, startW[i] = w;
        if (i == 0)
        {
            continue;
        }
        endH[i - 1] = h, endW[i - 1] = w;
    }
}
void input()
{
    for (int h = 1; h <= height; h++)
    {
        scanf("\n");
        for (int w = 1; w <= width; w++)
        {
            scanf("%c", &field[h][w]);
            setStart(h, w, field[h][w]);
        }
    }
}
bool isValid(int h, int w)
{
    return h >= 1 && h <= height && w >= 1 && w <= width && field[h][w] != 'X';
}
void setAnsToInf()
{
    for (int h = 1; h <= height; h++)
    {
        for (int w = 1; w <= width; w++)
        {
            ans[h][w] = inf;
        }
    }
}
int bfs(int i)
{
    setAnsToInf();
    ans[startH[i]][startW[i]] = 0;
    queue<P> que;
    que.push(P(startH[i], startW[i]));
    while (!que.empty())
    {
        P p = que.front();
        que.pop();
        for (int i = 1; i <= 4; i++)
        {
            if (!isValid(p.first + dh[i], p.second + dw[i]))
            {
                continue;
            }
            int newH = p.first + dh[i], newW = p.second + dw[i];
            if (ans[p.first][p.second] + 1 >= ans[newH][newW])
            {
                continue;
            }
            ans[newH][newW] = ans[p.first][p.second] + 1;
            que.push(P(newH, newW));
        }
    }
    return ans[endH[i]][endW[i]];
}
int main()
{
    scanf("%d%d%d", &height, &width, &count);
    input();
    ll result = 0LL;
    for (int i = 0; i < count; i++)
    {
        result += bfs(i);
    }
    printf("%lld\n", result);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值