您的位置:首页 > 产品设计 > UI/UE

hdu 1242 Rescue(BFS搜索)

2015-07-19 14:31 281 查看
 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242

 题       意:天使的朋友从r位置出发去a位置救天使。

 思       路:从a位置开始进行BFS遍历,找到到r位置时所花费的时间(也可用优先队列进行处理)。

 代码如下:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <algorithm>
using namespace std;
char vis[220][220];
int n, m, ans, x1, y1;
struct node
{
int x,y,t;
};
int dx[4]= {1,-1,0,0},dy[4]= {0,0,1,-1};
int bfs()
{
queue<node>q;
while( !q.empty() )
q.pop();
node kai,dai;
vis[x1][y1]='#';
kai.x=x1;
kai.y=y1;
kai.t=0;
q.push(kai);
while( !q.empty() )
{
kai = q.front();
q.pop();
if( vis[kai.x][kai.y] == 'r' )
return kai.t;
for( int i = 0 ; i < 4; i ++ )
{
int xx=kai.x+dx[i];
int yy=kai.y+dy[i];
if( yy > 0 && yy <= m && xx > 0 && xx <=n && vis[xx][yy] != '#' )
{
if( vis[xx][yy] == 'r' ) return kai.t+1;
dai.x=xx;
dai.y=yy;
dai.t=kai.t+1;
if( vis[xx][yy] == 'x' ) dai.t++;
q.push(dai);
vis[xx][yy]='#';
}
}
}
return -1;
}
int main()
{
while( scanf ( "%d %d", &n, &m ) != EOF )
{
for ( int i = 1; i <= n; i ++ )
for( int j = 1; j <= m; j ++ )
{
scanf ( " %c", &vis[i][j] );
if( vis[i][j] == 'a' )
{
x1=i;
y1=j;
}
}
ans=bfs();
if(ans>-1) printf("%d\n",ans);
else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm BFS