C++利用BFS算法求迷宫通关最短步骤以及路径

在算出最短的路径的基础上,在结构体中定义额外的string来记录每一步走的路径,并保留在队列中以此来实现记录路径的功能。 

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int a[100][100]={0};
int v[100][100]={0};
int flag=0;
struct point
{
	int x;
	int y;
	int step;
	string s;	
};
queue<point> r;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
string s[4]={"上","下","左","右"};
int main()
{
	int m,n;
	cin >> m >> n ;
	for(int i=0;i<m;i++)
	{
		for(int j=0;j<n;j++)
		{
			cin >> a[i][j] ;
		}
	}
	for(int i=0;i<m;i++)
	{
		for(int j=0;j<n;j++)
		{
			v[i][j]=1 ;
		}
	}
	int xStart,yStart;
	cin >> xStart >> yStart ;
	int xEnd,yEnd;
	cin >> xEnd >> yEnd ;
	xStart--;
	yStart--;
	xEnd--;
	yEnd--;
	point start;
	start.x=xStart;
	start.y=yStart;
	start.step=0;
	v[xStart][yStart]=2;
	r.push(start);
	
	while(!r.empty())
	{
		int x=r.front().x;
		int y=r.front().y;
		if(x==xEnd && y==yEnd)
		{
			flag=1;
			cout << "最短步骤" << r.front().step << endl ;
			cout << r.front().s << endl ;
			break;
		}
		
		for(int k=0;k<3;k++)
		{
			int tx,ty;
			tx=x+dx[k];
			ty=y+dy[k];
			if(a[tx][ty]==1 && v[tx][ty]==1)
			{
				point temp;
				temp.x=tx;
				temp.y=ty;
				if(k==0)
				{
					temp.s=r.front().s+"上";
				}
				if(k==1)
				{
					temp.s=r.front().s+"右";
				}
				if(k==2)
				{
					temp.s=r.front().s+"下";
				}
				if(k==3)
				{
					temp.s=r.front().s+"左";
				}
				v[tx][ty]=2;
				temp.step=r.front().step+1;
				r.push(temp);
			}
		}
		r.pop();
	}
	if(flag==0)
	{
		cout << "no answer!" << endl;
	}
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值