HDU–1242:Rescue (BFS)

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。HDU–1242:Rescue (BFS),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

1. 题目源地址:http://acm.hdu.edu.cn/showproblem.php?pid=1242

2. 易错点:可能存在多个朋友,即多个map[][]中有多个‘r’,所以起始点为Angel的位置,最短时间为到达最近的朋友的时间。

3. 源代码:

//HOJ--1242:Rescue      
#include<iostream>
#include<memory.h>
#include<stdio.h>
#include<queue>
using namespace std;

char map[210][210];
int visited[210][210];
int dx[]={1,-1,0,0};
int dy[]={0,0,-1,1};
int N,M;

struct node
{
   int x,y;
   int step;
}start,current,next;

bool InMap(int x,int y)
{
   if(x>=1 && x<=N && y>=1 && y<=M)
      return true;
   else
      return false;
}

int BFS()
{
    queue<node> Q;
    int i;
    
    start.step=0;
    Q.push(start);
    
    while(!Q.empty())
    {
       current=Q.front();
       Q.pop();
       
       for(i=0;i<4;i++)
       {
          next.x=current.x+dx[i];
          next.y=current.y+dy[i];
          next.step=current.step+1;
          
          if(map[next.x][next.y]=='x')
             next.step++;
          
          if(map[next.x][next.y]=='r')
             return next.step;
             
          if(!visited[next.x][next.y] && InMap(next.x,next.y) && map[next.x][next.y]!='#')
          {
             visited[next.x][next.y]=1;
             Q.push(next); 
          } 
       }
    }
   return 0;
}

int main()
{
    int i,j;
    while(cin>>N>>M)
    {
       getchar();
       memset(visited,0,sizeof(visited));
       
       for(i=1;i<=N;i++)
          for(j=1;j<=M;j++)
          {
             cin>>map[i][j];
             if(map[i][j]=='a')//可能存在多个朋友,即多个r,所以起始点为Angel的位置,最短时间为到达最近的朋友的 时间 
             {
                start.x=i;
                start.y=j;
             }
          }
       int ans=BFS();
       if(ans)   cout<<ans<<endl;
       else      cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/163034.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!