lanqiao.602 迷宫

该篇文章详细介绍了如何使用C++编程语言实现一个二维空间中的广度优先搜索(BFS)算法,用于寻找从给定起点到特定终点的路径,同时处理边界条件和避免重复路径。
摘要由CSDN通过智能技术生成

题目:

代码:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue> 
using namespace std;
char mp[31][51];   //稍微开大一点 
char k[4]={'D','L','R','U'};      //按字典序记录路径 
int dirx[]={1,0,0,-1},diry[]={0,-1,1,0};
int vis[30][50];  //以前用st数组标记 
struct node
{
	int x,y;	
	string path;
};   //这里一定要打分号。 
//struct node<queue> q;  乌鱼子这个写错了
queue<struct node>q;
void bfs()
{
	struct node start;
	struct node now;
	struct node next;
	start.x=0,start.y=0;
	start.path="";
	vis[0][0]=1;
	q.push(start);
	
	/*for(int i=0;i<4;i++)
		{
			
		}*/
	while(!q.empty())
		{
			now=q.front();
			q.pop();
			
			if(now.x==29&&now.y==49)
				{
				cout<<now.path;    //别忘了return
				return; 
				}
			
			for(int i=0;i<4;i++)
				{
					next.x=now.x+dirx[i];
					next.y=now.y+diry[i];
					if(next.x<0||next.x>=30||next.y<0||next.y>=50)
						continue;
					if(vis[next.x][next.y]==1||mp[next.x][next.y]=='1')  //不要忘记屏障这个条件 
						continue;
					
					vis[next.x][next.y]=1;
					next.path=now.path+k[i];   //Path一定要放在push前面 
					q.push(next);
					
					//path+=k[i];
					
				}
		}
	
}
 
int main()
{
	for(int i=0;i<30;i++)
		for (int j=0;j<50;j++)
			cin>>mp[i][j];
	bfs();
	return 0; 
 } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值