hdu1242 广搜+优先队列

有好多关于广搜的题目都是bfs+优先队列,,,其实这算法不是广搜,是最短路径的一种算法,只是因为输入数据的特殊性对每个顶点访问了一次(digkstra 最短路径对每边松弛一次,但每个点不一定只访问一次)
 #include<iostream>
 #include<queue>
 using namespace std;
 char map[205][205];
 int xx[4]={0,1,0,-1};
 int yy[4]={1,0,-1,0};
 struct node
 {
     int x,y;
     int ti;
     friend bool operator <(node a,node b)
     {
         return a.ti>b.ti;
     }
     node():ti(0){}
 };
 int main()
 {
     int n,m;
     while(cin>>n>>m)
     {
         int i,j;
         priority_queue<node> q;
         node a[10];
         node s1;
         node s2;
         int k=0;
         for(i=1;i<=n;i++)
         {
             for(j=1;j<=m;j++)
             {
                 cin>>map[i][j];
                 if(map[i][j]=='a')
                 {
                     s1.x=i;
                     s1.y=j;
                 }
             }
         }
         q.push(s1);
         map[s1.x][s1.y]='#';
         while(!q.empty())
         {
             s1=q.top();
             q.pop();
             for(i=0;i<4;i++)
             {
                 s2.x=s1.x+xx[i];
                 s2.y=s1.y+yy[i];
                 if(s2.x<1||s2.x>n||s2.y<1||s2.y>m||map[s2.x][s2.y]=='#')
                     continue;
                 if(map[s2.x][s2.y]=='x')
                 {
                     s2.ti=s1.ti+2;
                     map[s2.x][s2.y]='#';
                     q.push(s2);
                 }
                 else
                 {
                     s2.ti=s1.ti+1;
                     if(map[s2.x][s2.y]=='r')
                         a[k++]=s2;
                     map[s2.x][s2.y]='#';
                     q.push(s2);
                 }
 
             }
 
         }
         int min=10000000;
         for(i=0;i<k;i++)
         {
             if(a[i].ti<min)
                 min=a[i].ti;
         }
         if(i==0)
             cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
         else
             cout<<min<<endl;
 
     }
     return 0;
 }
 







   

你可能感兴趣的:(hdu1242 广搜+优先队列)