hdu1242----------bfs+优先队列

不是找最短路,而是找最短时间。  用优先队列,优先出队耗时最少的点。

从这道题可以深刻理解队列在bfs中的用途,它仅仅是作为出队的工具,你想找对短路行,找最短时间也行,找最少拐点也可以。

总之,只要你定义好,按什么优先出队就行了。

AC:

#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;

char map[205][205];
int visit[205][205];                //记录走到该点所花费的时间
int fang[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct info
{
 int x;
 int y;
 int num;               //记录从起点,走到这个点所化的时间
 bool operator < (const info &a) const                     //按num从小到大排序
 {
  return a.num<num;
 }
};
int n,m;                         //n行,     m列

int bfs(int x1,int y1)
{
 int i,j;
 priority_queue<info> qu;
 info t,tt;
 t.x=x1;
 t.y=y1;
 t.num=0;
 map[t.x][t.y]='#';
 qu.push(t);
 while(!qu.empty())
 {
  t=qu.top();
  qu.pop();
  for(i=0;i<4;i++)
  {
   tt.x=t.x+fang[i][0];
   tt.y=t.y+fang[i][1];
   tt.num=t.num+1;
   if(tt.x<1||tt.y<1||tt.x>n||tt.y>m)
   continue;
   if(map[tt.x][tt.y]=='r')
   {
    return tt.num;
   }
   if(map[tt.x][tt.y]=='x')
   {
    tt.num++;
   }
   if(map[tt.x][tt.y]!='#')
   {
    map[tt.x][tt.y]='#';   
    qu.push(tt);
   }
  }
 }
 return 0;
}

int main()
{
 int i,j,k;
 int x1,y1;
 while(scanf("%d%d",&n,&m)!=EOF)
 {
  getchar();
  for(i=1;i<=n;i++)
  {
   for(j=1;j<=m;j++)
   {
    scanf("%c",&map[i][j]);
       if(map[i][j]=='a')
       {
        x1=i;
        y1=j;
       }
      }
   getchar();
  }
  
  k=bfs(x1,y1);
  if(k>0)
  printf("%d\n",k);
  else
  printf("Poor ANGEL has to stay in the prison all his life.\n");
 }
 return 0;
}
 

posted on 2012-04-06 13:20  hrbust_09zhangyabin  阅读(217)  评论(0编辑  收藏  举报