hdu2612 简单两次广搜

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
int n,m;
int dir[4][2]={-1,0,0,-1,1,0,0,1};
queue<pair<int,int> > q;
char map[220][220];
int step[220][220];
int visit[220][220];
int ans[220][220];
void bfs(int a,int b){
     visit[a][b]=1;
     while(!q.empty()){
       q.pop();

     }
     q.push(make_pair(a,b));
     pair<int,int> tmp;
     while(!q.empty()){
         tmp=q.front();
         q.pop();
         if(map[tmp.first][tmp.second]=='@'){
             //cout<<tmp.first<<tmp.second<<endl;
             ans[tmp.first][tmp.second]+=step[tmp.first][tmp.second];//两次广搜记录两人到'@'的总的路径和
         }
         for(int k=0;k<4;k++){
            int ii=tmp.first+dir[k][0];
            int jj=tmp.second+dir[k][1];
            //cout<<ii<<"jkj"<<jj<<endl;
            if(ii>=0&&jj>=0&&ii<n&&jj<m&&!visit[ii][jj]&&map[ii][jj]!='#'){
                  //cout<<ii<<"jkj"<<jj<<endl;
                  visit[ii][jj]=1;
                  step[ii][jj]=step[tmp.first][tmp.second]+1;
                  q.push(make_pair(ii,jj));
            }




         }



     }




}
int main(){
    while(cin>>n>>m){
        memset(ans,0,sizeof(ans));
        memset(step,0,sizeof(step));
        memset(visit,0,sizeof(visit));
        int s1i,s1j;
        int s2i,s2j;
        for(int i=0;i<n;i++)
          for(int j=0;j<m;j++){
             cin>>map[i][j];
             if(map[i][j]=='Y'){
                 s1i=i;
                 s1j=j;
             }
             if(map[i][j]=='M')
               {
                   s2i=i;
                   s2j=j;
               }
          }
          //cout<<s2i<<"jk"<<s2j<<endl;
          bfs(s1i,s1j);
          memset(step,0,sizeof(step));
          memset(visit,0,sizeof(visit));
          bfs(s2i,s2j);
          int fans=101010101;
          for(int i=0;i<n;i++)
              for(int j=0;j<m;j++)
                if(ans[i][j]){
                   fans=min(fans,ans[i][j]);
                }
         cout<<fans<<endl;


    }





}

你可能感兴趣的:(广搜)