HDU - 2612 Find a way

HDU - 2612 题目链接
思路
两遍bfs,第一遍以Y为起点,如果这个点是KFC则标记上Y到这个点的步数,
第二遍以M为起点,如果这个点是KFC则加上M到这个点的步数,
bfs的时候注意,判断的时候不能加上continue语句,因为后面有一些点的最短步数是与这个点有关的,这样可能会导致记录的点的步数不全面

//Powered by CK
#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
#include<algorithm>
using namespace std;
struct point {
    int x,y,step;
    point(int a,int b,int c): x(a), y(b),step(c) {}
};
const int maxn = 210;
const int ax[4] = {1,0,0,-1};
const int ay[4] = {0,1,-1,0};
char maze[maxn][maxn];
int visity[maxn][maxn], visitm[maxn][maxn],ans[maxn][maxn],n,m;
void bfsy(int x,int y) {
    queue<point>a;
    a.push(point(x, y, 0));
    visity[x][y] = 1;
    while(!a.empty()) {
        point temp = a.front();
        a.pop();
        if(maze[temp.x][temp.y] == '@')
            ans[temp.x][temp.y] = temp.step;
        for(int i = 0; i < 4; i++) {
            int tempx = temp.x + ax[i];
            int tempy = temp.y + ay[i];
            if(!visity[tempx][tempy] && maze[tempx][tempy] != '#' && tempx >=0 && tempx < n && tempy >= 0 && tempy < m) {
                visity[tempx][tempy] = 1;
                a.push(point(tempx,tempy,temp.step + 1));
            }
        }
    }
}
void bfsm(int x,int y) {
    queue<point>a;
    a.push(point(x,y,0));
    visitm[x][y] = 1;
    while(!a.empty()) {
        point temp = a.front();
        a.pop();
        if(maze[temp.x][temp.y] == '@' && ans[temp.x][temp.y])
            ans[temp.x][temp.y] += temp.step;
        for(int i = 0; i < 4; i++) {
            int tempx = temp.x + ax[i];
            int tempy = temp.y + ay[i];
            if(!visitm[tempx][tempy] && maze[tempx][tempy] != '#' && tempx >=0 && tempx < n && tempy >= 0 && tempy < m) {
                visitm[tempx][tempy] = 1;
                a.push(point(tempx,tempy,temp.step + 1));
            }
        }
    }
}
int main() {
    while(cin >> n >> m) {
        int xy,yy,xm,ym;
        memset(visity,0,sizeof(visity));
        memset(visitm,0,sizeof(visitm));
        memset(ans,0,sizeof(ans)); 
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++) {
                cin >> maze[i][j];
                if(maze[i][j] == 'Y')   xy = i, yy = j;
                if(maze[i][j] == 'M')   xm = i, ym = j;
            }
        bfsy(xy,yy);
        bfsm(xm,ym);
        int sum = 0x3f3f3f3f;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(ans[i][j])
                    sum = min(sum,ans[i][j]);
        cout << sum * 11 <<endl;
    }
    return 0;
}
posted @ 2020-01-07 15:04  lifehappy  阅读(101)  评论(0编辑  收藏  举报