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]){
    queues;
    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<
//      cout<
        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 "<
                } 
        printf("%d\n",min*11);

    }   
} 

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

你可能感兴趣的:(BFS)