hdu1242

整个题目没有太大的难度,就是搜索计时,求最小的时间的问题,但是在做的的时候用到了优先队列,在这种优先队列,优先队列对于像这种广度搜索还是非常不错的。在以后做题的时候要多多考虑这些方法。

#include <cstdio>
#include <string.h>
#include <iostream>
#include <queue>
#include<functional>
#include <cstdlib>
using namespace std;
struct node
{
	friend bool operator <(node n1,node n2)
   {
	   return n1.time>n2.time;
   }
     int x;
     int y;
     int time;     
};
    int v[202][202];
    char map[202][202];
    int m,n;
    int x,y;
int BFS(int a,int b)
{
     int i,j,flag=1;
     int k=0;
     node st,en;
     st.x=a;
     st.y=b;
     st.time=0;
     priority_queue<node>q;//定义一个优先队列
     q.push(st);
     while(!q.empty())//开始进入搜索
	 {
        st=q.top();
		q.pop();
        i=st.x;
        j=st.y;
        if(i==x&&j==y)
         return st.time+1;
//下面分了四中情况,这样列举几种情况还是比较复杂繁琐的,看了一些大牛的博客 ,貌似都比我的好,用数组的比较多  下次我可以试一试
      if(map[i+1][j]!='#'&&v[i+1][j]==0&&i+1<n&&i!=-1)
	  {
          if(map[i+1][j]=='x')
		  {
                 en.time=st.time+2;
		  }
         else
           en.time=st.time+1;
           en.x=i+1;
           en.y=j;
           q.push(en);
           v[i+1][j]=1;
	  }
          if(map[i][j+1]!='#'&&v[i][j+1]==0&&j+1<m&&i!=-1)
		  {
            if(map[i][j+1]=='x')
			{
                   en.time=st.time+2;
			}
         else
          en.time=st.time+1;
          en.x=i;
          en.y=j+1;
          q.push(en);
          v[i][j+1]=1;
		  }
      if(map[i][j-1]!='#'&&v[i][j-1]==0&&j-1>=0&&i!=-1)
	  {
         if(map[i][j-1]=='x')
		 {
                   en.time=st.time+2;
		 }
         else
          en.time=st.time+1;
          en.x=i;
          en.y=j-1;
          q.push(en);
          v[i][j-1]=1;
	  }
      if(map[i-1][j]!='#'&&v[i-1][j]==0&&i-1>=0&&i!=-1)
	  {
           if(map[i-1][j]=='x')
		   { 
                   en.time=st.time+2;
		   }
          else
              en.time=st.time+1;
              en.x=i-1;
              en.y=j;
              q.push(en); 
	  }
	 }
   return -1;
}


int main()
{
     int a,b;
     int i,j;
    //freopen("in.txt","r",stdin);
   while(scanf("%d%d",&n,&m)!=EOF)
   { 
       memset(v,0,sizeof(v));
          for(i=0;i<n;i++)
		  {
            scanf("%s",&map[i]);
           for(j=0;j<m;j++)
		   {
            if(map[i][j]=='r')
			{
                 a=i;b=j;
			}
            if(map[i][j]=='a')
			{
              x=i;y=j;
			}
		   }
		 }
        int count= BFS(a,b);
            if(count==-1)
           printf("Poor ANGEL has to stay in the prison all his life.\n");
           else
           printf("%d\n",count-1);
   }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值