HDU-OJ 杭电2612 Find a way 双层BFS

#include "iostream"
#include "cstring"
#include "queue"
#define INF 0x3f3f3f3f
using namespace std;

char a[201][201];
int n, m;

struct node{
    int x, y;
    int step;
}now,start1,start2;


//记录 
char vis[201][201];
int kfc1[201][201];
int kfc2[201][201];

bool check(node x){
    if(x.x >= 0 && x.x < n && x.y >= 0 && x.y < m) return true;
    else return false;
}

void bfs(node now,int(*kfc)[201]){
    queue<node>s;
    memcpy(vis,a,sizeof(a));
    int dx[] = {1,-1,0,0};
    int dy[] = {0,0,1,-1}; 
    now.step = 0;
    s.push(now);
    while(!s.empty()){
        now = s.front();s.pop();
        if (vis[now.x][now.y]=='#')continue;
        if(vis[now.x][now.y]=='@') kfc[now.x][now.y] = now.step;
        vis[now.x][now.y] = '#';
        for(int i = 0 ; i < 4; i++){
            node next;
            next.x = now.x + dx[i];
            next.y = now.y + dy[i];
            next.step = now.step + 1;
            if(check(next)){
                if(vis[next.x][next.y] == '.' || vis[next.x][next.y] == '@') 
                    s.push(next);
                else continue;
            }
        }
    }
//  for(int i = 0;i < n; i++){
//      for(int j = 0; j < m; j++){
//          cout << kfc[i][j]<<" "; 
//      }
//      cout << endl;
//  }


}

int main(){
    while(scanf("%d%d",&n,&m)!=EOF){
        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'){
                    start1.x = i;
                    start1.y = j;
                    start1.step = 0;
                }
                if(a[i][j]=='M'){
                    start2.x = i;
                    start2.y = j;
                    start2.step = 0;
                }
            } 
//      cout<<start1.x<<" " <<start1.y<<endl;
//      cout<<start2.x<<" " <<start2.y<<endl;
        memset(kfc1,0x3f,sizeof(kfc1));
        memset(kfc2,0x3f,sizeof(kfc2));
        bfs(start1,kfc1);
        bfs(start2,kfc2);

        int min = INF;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++){
                    if(kfc1[i][j]!=INF && kfc2[i][j]!=INF&& (kfc1[i][j]+kfc2[i][j])< min)
                        min = kfc1[i][j] + kfc2[i][j];
//                      cout<<"min "<<min<<endl;
                } 
        printf("%d\n",min*11);

    }   
} 

还是要注意,continue不加会超时和超内存,一定是因为栈的问题导致的。 还有就是千万注意&&和||,这些细节害我查了3个小时的错。
最好是push完!!就标记已经访问过

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值