hdu_1728_逃离迷宫

本文提供了一种使用广度优先搜索(BFS)解决迷宫问题的方法,通过跟踪最少转弯次数来寻找从起点到终点的路径。特别地,介绍了如何在遇到障碍物时更新方向和转弯计数。

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

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1728

#include <iostream>
#include <queue>
using namespace std;
int r,c,k,visit[101][101];
char map[101][101];
int dir_x[4] = {0,1,0,-1},dir_y[4] = {1,0,-1,0};
typedef struct 
{
	int x;
	int y;
	int turn;//转弯次数 
}node;

node s,e;

void bfs()
{
	queue<node> que;
	node first,next;
	if(s.x == e.x && s.y == e.y)//特殊情况,起点和终点相同 
	{
		cout << "yes" << endl;
		return;
	}
	s.turn = -1;//初始化起点的方向为-1,即起点到四周的转弯次数为0 
	que.push(s);
	 
	while(!que.empty())
	{
		first = que.front();
		que.pop();
		if(first.x == e.x && first.y == e.y && first.turn <= k)
		{
			cout << "yes" << endl;
			return;
		}
		int i;
		for(i = 0;i < 4;i++)
		{
			next.x = first.x + dir_x[i];
			next.y = first.y + dir_y[i];
			while(next.x >= 1 && next.x <= r && next.y >= 1 && next.y <= c && map[next.x][next.y] == '.')
			{
				if(visit[next.x][next.y] == 0)//没被访问过 
				{
					next.turn = first.turn + 1;
					visit[next.x][next.y] = 1;//标记已经访问过了 
					que.push(next);
				}
				next.x += dir_x[i];//确定一个方向,一直朝这个方向走,直到不能走位置才改变方向 
				next.y += dir_y[i];
			}
		}
	}
	cout << "no" << endl;
	return;
}
int main(int argc, char *argv[])
{
	int t,i,j,x1,y1,x2,y2;
	cin >> t;
	while(t--)
	{
		memset(visit,0,sizeof(visit));
		cin >> r >> c;
		for(i = 1;i <= r;i++)
			for(j = 1;j <= c;j++)
				cin >> map[i][j];
		cin >> k >> x1 >> y1 >> x2 >> y2;
		s.x = y1;
		s.y = x1;
		e.x = y2;
		e.y = x2;
		bfs();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值