Hdu2612 Find a way【简单bfs】

http://acm.hdu.edu.cn/showproblem.php?pid=2612

走迷宫题目变型,简单bfs

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
template <class T> void checkmin(T &t,T x) {if(x < t) t = x;}
template <class T> void checkmax(T &t,T x) {if(x > t) t = x;}
template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;}
template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;}
typedef pair <int,int> PII;
typedef pair <double,double> PDD;
typedef long long ll;
#define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++)
const int N = 222;
int n , m;
char maze[N][N];
int ma1[N][N] , ma2[N][N] , ma[N][N];
int yx , yy , mx , my;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
bool inmap(int x,int y) {
    return x >= 0 && x < n && y >= 0 && y < m;
}
struct node {
    int x , y;
};
queue <node> q;
void bfs(int sx,int sy) {
    for(int i=0;i<n;i++)
    for(int j=0;j<m;j++) ma[i][j] = -1;
    ma[sx][sy] = 0;
    while(!q.empty()) q.pop();
    node u , v;
    u.x = sx , u.y = sy;
    q.push(u);
    while(!q.empty()) {
        u = q.front(); q.pop();
        for(int i=0;i<4;i++) {
            int x = u.x + dir[i][0];
            int y = u.y + dir[i][1];
            if(!inmap(x,y) || maze[x][y] == '#') continue;
            if(ma[x][y] == -1 || ma[u.x][u.y] + 1 < ma[x][y]) {
                ma[x][y] = ma[u.x][u.y] + 1;
                v.x = x , v.y = y;
                q.push(v);
            }
        }
    }
}
int main() {
    while(~scanf("%d%d",&n,&m)) {
        for(int i=0;i<n;i++) scanf("%s",maze[i]);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) {
            if(maze[i][j] == 'Y') yx = i , yy = j;
            if(maze[i][j] == 'M') mx = i , my = j;
        }
        bfs(yx,yy);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) ma1[i][j] = ma[i][j];
        bfs(mx,my);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) ma2[i][j] = ma[i][j];
        int ans = (1<<29);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) {
            if(maze[i][j] == '@' && ma1[i][j]!=-1) {
                checkmin(ans , ma1[i][j]+ma2[i][j]);
            }
        }
        printf("%d\n" , 11 * ans);
    }
    return 0;
}

 

posted @ 2013-03-30 02:21  aiiYuu  阅读(151)  评论(0)    收藏  举报