hdu 1242 rescue bfs+优先队列

#include
#include
#include
#include
using namespace std;
int vis[205][205];
char mp[205][205];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int sx,sy,ex,ey,tx,ty,step,n,m;
struct node{
 int x,y,step;
 friend bool operator<(node n1,node n2)
 {
  return n1.step>n2.step;
 }
}pos,now,nt;
void bfs()
{
 pos.x=sx;
 pos.y=sy;
 pos.step=0;
 priority_queue<node> q;
 q.push(pos);
 vis[sx][sy]=1;
 
 while(!q.empty())
 {
  now=q.top();
  q.pop();
  if(now.x==ex&&now.y==ey)
  {
   step=1;
   printf("%d\n",now.step);
   return;
  }
  for(int i=0;i<4;i++)
  {
   tx=now.x+dir[i][0];
   ty=now.y+dir[i][1];
   
   if(tx>=0&&tx<n&&ty>=0&&ty<m&&mp[tx][ty]!='#'&&!vis[tx][ty])
   {
    if(mp[tx][ty]=='x')
    {
     nt.x=tx;
     nt.y=ty;
     nt.step=now.step+2;
     vis[tx][ty]=1;
     q.push(nt);
    }
    else
    {
     nt.x=tx;
     nt.y=ty;
     nt.step=now.step+1;
     vis[tx][ty]=1;
     q.push(nt);
    }
  //  printf("nt.x=%d,nt.y=%d,nt.step=%d\n",nt.x,nt.y,nt.step);
   }
  }
 }
}
int main(void)
{
 while(~scanf("%d%d",&n,&m))
 {
  for(int i=0;i<n;i++)
  {
   for(int j=0;j<m;j++)
   {
    scanf(" %c",&mp[i][j]);//注意读取方式 
    if(mp[i][j]=='a')
    {
     sx=i;
     sy=j;
   //  printf("%d %d\n",sx,sy);
    }
    
    if(mp[i][j]=='r')
    {
     ex=i;
     ey=j;
    }
   }
  }
  
  memset(vis,0,sizeof(vis));
  step=0;
  bfs();
  if(!step)
   printf("Poor ANGEL has to stay in the prison all his life.\n"); 
 }
 return 0;
}

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