HDU-1242-Rescue

本文介绍使用BFS算法解决迷宫问题,通过构建状态节点并进行广度优先搜索,最终找到从起点到终点的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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

 

水题,bfs

代码

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;

int n,m,success;
int stx,sty,ex,ey;
char map[210][210];
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};

struct node
{
int x,y,g,cnt;
};

queue<node> q;

void bfs()
{
node s,e;
while(q.size())
q.pop();
s.x=stx; s.y=sty; s.cnt=0; s.g=0;
q.push(s);
while(q.size())
{
s=q.front();
q.pop();
if(s.x==ex&&s.y==ey)
{
success=1;
printf("%d\n",s.cnt);
return ;
}
for(int i=0;i<4;i++)
{
e.x=s.x+dx[i]; e.y=s.y+dy[i];
if(e.x>=0&&e.x<n&&e.y>=0&&e.y<m&&map[e.x][e.y]!='#')
{
if(s.g==0)
{
if(map[e.x][e.y]=='x')
{
e.g=1;
e.cnt=s.cnt+1;
q.push(e);
map[e.x][e.y]='#';
}
else
{
e.g=0;
e.cnt=s.cnt+1;
q.push(e);
map[e.x][e.y]='#';
}
}
else
{
s.g=s.g-1;
s.cnt=s.cnt+1;
q.push(s);
}
}
}
}
}

int main(void)
{
int i,j;
while(scanf("%d%d",&n,&m)==2)
{
getchar();
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='r')
{
stx=i; sty=j;
}
else if(map[i][j]=='a')
{
ex=i; ey=j;
}
}
getchar();
}
success=0;
bfs();
if(!success)
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}

 

转载于:https://www.cnblogs.com/liudehao/p/4138137.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值