HDU 2612 Find a way(BFS)

45 篇文章 0 订阅
44 篇文章 0 订阅

一开始想法比较傻,对每一个KFC为起点BFS,后来发现其实我们只需要对这两个人为起点BFS一遍就行了,将遇到的每个KFC记录在vector里,但是WA,后来又发现不需要保存的vector里,直接用两个数组记录路径就OK了,成功AC。    之前那个方法肯定也行,不知道哪里出现了BUG。。。

细节参见代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int INF = 1e9;
const int maxn = 205;
int n,m,T,d1[maxn][maxn],d2[maxn][maxn];
char a[maxn][maxn];
struct node{
    int r,c;
    node(int r=0, int c=0):r(r),c(c) {}
    bool operator == (const node& rhs) const {
        return r == rhs.r && c == rhs.c;
    }
}s,t;
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
int bfs1(node v) {
    queue<node> q;
    memset(d1,-1,sizeof(d1));
    d1[v.r][v.c] = 0;
    q.push(v);
    while(!q.empty()) {
        node u = q.front(); q.pop();
        for(int i=0;i<4;i++) {
            int x = u.r + dx[i], y = u.c + dy[i];
            if(x < 0 || x >= n || y < 0 || y >= m) continue;
            if(a[x][y] != '#' && d1[x][y] == -1) {
                d1[x][y] = d1[u.r][u.c] + 1;
                q.push(node(x,y));
            }
        }
    }
    return -1;
}
int bfs2(node v) {
    queue<node> q;
    memset(d2,-1,sizeof(d2));
    d2[v.r][v.c] = 0;
    q.push(v);
    while(!q.empty()) {
        node u = q.front(); q.pop();
        for(int i=0;i<4;i++) {
            int x = u.r + dx[i], y = u.c + dy[i];
            if(x < 0 || x >= n || y < 0 || y >= m) continue;
            if(a[x][y] != '#' && d2[x][y] == -1) {
                d2[x][y] = d2[u.r][u.c] + 1;
                q.push(node(x,y));
            }
        }
    }
    return -1;
}
int main() {
    while(~scanf("%d%d",&n,&m)) {
        for(int i=0;i<n;i++)
            scanf("%s",a[i]);
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                if(a[i][j] == 'Y') s = node(i,j);
                else if(a[i][j] == 'M') t = node(i,j);
        bfs1(s); bfs2(t);
        int ans = INF;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                if(a[i][j] == '@'&&d1[i][j]!=-1&&d2[i][j]!=-1) ans = min(ans,d1[i][j]+d2[i][j]);
        printf("%d\n",ans*11);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值