HDU - 2612 - Find a way 【BFS】

题意: 输出Y和M 到图中 ‘@’的最小步数之和

题解: 用三维数组分别储存Y 和 M 到 图中的每一点的步数,输出最小的步数和;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define INF 0x7ffffff
using namespace std;
const int maxn = 205;
char mp[maxn][maxn];
bool vis[maxn][maxn];
int ans[2][maxn][maxn];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int n, m;
struct node
{
    int x, y;
    int step;
};
void bfs(node S, int x)
{
    memset(vis, 0, sizeof(vis));

    queue<node> q;
    vis[S.x][S.y] = true;
    q.push(S);

    while(!q.empty())
    {
        node now = q.front();
        q.pop();
        node next;
        for(int i = 0; i < 4; i++)
        {
            next.x = now.x + dir[i][0];
            next.y = now.y + dir[i][1];
            if(next.x < n && next.x >= 0 && next.y < m && next.y >= 0 && !vis[next.x][next.y] && mp[next.x][next.y] != '#')
            {
               next.step = now.step + 1;
               vis[next.x][next.y] = true;
               ans[x][next.x][next.y] += ans[x][now.x][now.y] + 1;
               q.push(next);
            }
        }
    }
}

int main()
{
    while(~scanf("%d%d", &n, &m))
    {
        memset(mp, 0, sizeof(mp));
         memset(ans, 0, sizeof(ans));
        node S1, S2;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
            {
                cin >> mp[i][j];
                if(mp[i][j] == 'Y')
                {
                    S1.x = i, S1.y = j;
                }
                else if(mp[i][j] == 'M')
                {
                    S2.x = i, S2.y = j;
                }
            }

        bfs(S1, 0);
        bfs(S2, 1);
       int sum = INF;
         for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
            {
                if(vis[i][j] != false && mp[i][j] == '@')
                sum = min(sum, ans[0][i][j] + ans[1][i][j]);
            }

            cout << sum * 11 << endl;

    }
}
/*
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值