hdu1242(bfs+优先队列)

    xiaoxiao2021-03-25  79

    #include<bits/stdc++.h> using namespace std; const int maxn=250; char a[maxn][maxn]; int vis[maxn][maxn]; int dir[4][2]= {1,0,-1,0,0,1,0,-1}; int n,m,countt=0; struct node {     int x;     int y;     int step;     friend bool operator <(node t1, node t2) //自定义优先级     {         return t1.step > t2.step ;     } }; int bfs(int x,int y) {     node now,next;     priority_queue<node>q;     now.x=x;     now.y=y;     now.step=0;     q.push(now);     while(!q.empty())     {         now=q.top();         q.pop();         if(a[now.x][now.y]=='r')         {             countt=now.step;             return countt;         }         for(int i=0; i<4; i++)         {             next.x=now.x+dir[i][0];             next.y=now.y+dir[i][1];             if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&a[next.x][next.y]!='#'&&vis[next.x][next.y]==0)             {                 vis[next.x][next.y]=1;                 next.step=now.step+1;                 if(a[next.x][next.y]=='x')                 {                     a[next.x][next.y]='.';                     next.step++;                 }                 q.push(next);             }         }     }     return -1; } int main() {     while(scanf("%d%d",&n,&m)!=EOF)     {         if(n==0&&m==0) break;         memset(vis,0,sizeof(vis));         for(int i=0; i<n; i++)         {             for(int j=0; j<m; j++)             {                 cin>>a[i][j];             }         }         int num1,num2;         for(int i=0; i<n; i++)         {             for(int j=0; j<m; j++)             {                 if(a[i][j]=='a')                 {                     num1=i;                     num2=j;                 }             }         }         int min_sum=0;         min_sum=bfs(num1,num2);         if(min_sum==-1) printf("Poor ANGEL has to stay in the prison all his life.\n");         else printf("%d\n",min_sum);     }     return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-12466.html

    最新回复(0)