hdu 1242

本文介绍了一道经典的图遍历问题HDU 1242,通过使用广度优先搜索(BFS)结合优先队列来解决迷宫寻路问题。文中提供了一个详细的C++实现示例,展示了如何定义节点结构体、比较运算符以及优先队列的使用方法。

http://acm.hdu.edu.cn/showproblem.php?pid=1242

 用bfs做,要用优先队列

#include<iostream>
#include<string>
#include<queue>
using namespace std;
int sx,sy,ex,ey;
int n,m;
int map[205][205];
int dis[4][2]={0,1,1,0,0,-1,-1,0};
struct node{
 int x,y;
 int step;
 friend bool operator<(node a,node b)   //优先队列必须写的
 {
  return b.step<a.step;
 }
};
bool cmp(int a,int b)                     //判断函数
{
 if(a<0||a>=n||b<0||b>=m) return 1;
 if(map[a][b]==1) return 1;
 return 0;
}
int bfs()
{
 priority_queue<node>q;          //优先队列的申明
 node cur,next;
 int i;
 cur.x=sx;
 cur.y=sy;
 cur.step=0;
 map[cur.x][cur.y]=1;

 q.push(cur);
 while(!q.empty())
 {
  cur=q.top();
  
  if(cur.x==ex&&cur.y==ey) return cur.step;   //如果到达出口就跳出
  q.pop();
  for(i=0;i<4;i++)                              //往四个方向进行搜索
  {
   next.x=cur.x+dis[i][0];
   next.y=cur.y+dis[i][1];

   if(cmp(next.x,next.y)) continue ;
   if(map[next.x][next.y]==-1) next.step=cur.step+2;   
   else next.step=cur.step+1;   
   map[next.x][next.y]=1;
   q.push(next);
  }
 }
 return 0;
}
int main()
{
 int i,j;
 int a,b;
 char str;
 while(cin>>n>>m)
 {
  memset(map,0,sizeof(map));    //一定要初始化
  for(i=0;i<n;i++)
  {
   
   for(j=0;j<m;j++)
   {
    cin>>str;
    if(str=='a') {sx=i;sy=j;}                     //朋友可能有多个,所以从天使开始搜索
    else if(str=='r') {ex=i;ey=j;}
    else if(str=='x') {map[i][j]=-1;}
    else if(str=='.') {map[i][j]=0;}
    else if(str=='#') {map[i][j]=1;}
   }
  }
  int sum=bfs();
  if(sum==0) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
  else cout<<sum<<endl;
 }
 return 0;
}

  

转载于:https://www.cnblogs.com/wuyanjun/archive/2013/05/19/3085025.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值