HDU2612 BFS

  题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2612 , 一道比较简单的广搜(BFS)题目。


算法:

  设置两个dist[][]数组,记录Y和M到几个KFC的距离,最后求两个dist的和的最小值即可。

  还有,Y是可以走M的位置的,同理,M也可以走Y的位置,不用纠结这个问题。有一点要注意的就是有的KFC是Y或M无法到达的,所以在最后求最小值的时候要注意这个KFC是否访问过。

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;
#define LL __int64
#define eps 1e-8
#define INF 1e8
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const int MOD = 2333333; 
const int maxn = 200 + 5;
struct Pos {
    int x , y;
};
Pos dir[4] = {{-1 , 0} , {0 , 1} , {1 , 0} , {0 , -1}};
vector <Pos> kfc; 
int dist1[maxn][maxn] , dist2[maxn][maxn];
int vis[maxn][maxn] , dist[maxn][maxn];
char map[maxn][maxn];
int n , m;

bool place(Pos a) 
{
    if(a.x < 0 || a.y < 0 || a.x >= n || a.y >= m || map[a.x][a.y] == '#' || vis[a.x][a.y])
        return false;
    return true;
}
void BFS(Pos start , int a[][maxn])
{
    memset(vis , 0 , sizeof(vis));
    queue <Pos> que;
    que.push(start);
    vis[start.x][start.y] = 1;
    dist[start.x][start.y] = 0;
    while(!que.empty()) {
        Pos u = que.front();
        que.pop();
        for(int i = 0 ; i < 4 ; i++) {
            Pos tmp;
            tmp.x = u.x + dir[i].x;
            tmp.y = u.y + dir[i].y;
            if(!place(tmp))
                continue;
            else {
                que.push(tmp);
                vis[tmp.x][tmp.y] = 1;
                dist[tmp.x][tmp.y] = dist[u.x][u.y] + 1;
                if(map[tmp.x][tmp.y] == '@')
                    a[tmp.x][tmp.y] = dist[tmp.x][tmp.y];
            }
        }
    }
}
int main() 
{
    int i , j;
    Pos start , end;
    char ch;
    while(~scanf("%d %d" , &n , &m))
    {
        memset(dist1 , 0 , sizeof(dist1));
        memset(dist2 , 0 , sizeof(dist2));
        kfc.clear();
        for(i = 0 ; i < n ; i++)
            scanf("%s" , map[i]);
        for(i = 0 ; i < n ; i++) {
            for(j = 0 ; j < m ; j++) {
                if(map[i][j] == 'Y') {
                    start.x = i;
                    start.y = j;
                } else if(map[i][j] == 'M') {
                    end.x = i;
                    end.y = j;
                } else if(map[i][j] == '@') {
                    Pos tmp = {i , j};
                    kfc.push_back(tmp);
                }
            }
        }
        BFS(start , dist1);
        BFS(end , dist2);
        int Min = INF;
        for(i = 0 ; i < kfc.size() ; i++) {
            int x = kfc[i].x;
            int y = kfc[i].y;
            if(Min > dist1[x][y] + dist2[x][y] && dist1[x][y] && dist2[x][y])
                Min = dist1[x][y] + dist2[x][y];
        }
        printf("%d
" , 11 * Min);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/H-Vking/p/4336272.html