迷宫问题

本文介绍了一种使用广度优先搜索(BFS)解决迷宫最短路径问题的方法,并提供了一个具体的C++实现示例。该算法从迷宫入口出发,通过遍历所有可能的方向来寻找到达出口的最短路径。

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


…11111111111111111111111111111
11.111111……..1111111111.1111
11.111111..111.11111111…..1111
11.11111111111.1111111111.111111
11.111111……………..111111
11.111111.11111111111.11111.1111
11.111111.11111111111.11111..111
11……….111111111.11111.1111
11111.111111111111111.11….1111
11111.111111111111111.11.11.1111
11111.111111111111111.11.11.1111
111…111111111111111.11.11.1111
111.11111111111111111….11.1111
111.11111111111111111111111.1111
111.1111.111111111111111……11
111.1111…….111111111.1111.11
111.1111.11111.111111111.1111.11
111……11111.111111111.1111111
11111111111111.111111111.111…1
11111111111111……………1.1
111111111111111111111111111111..

如上图的迷宫,入口,出口分别:左上角,右下角
“1”是墙壁,”.”是通路
求最短需要走多少步?

#include<iostream>
#include<string>
#include<queue>
using namespace std;
int mp[100][100];
int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
int vis[100][100];
int dis[100][100];
struct d{
	int x,y;
	int step;
	void creat(int a,int b,int s)
	{
		x=a;
		y=b;
		step=s;
	}
};
int n=21;
int m=31;
void bfs()
{
	queue<d> Q;
	d node;
	node.x=0;
	node.y=0;
	node.step=0;
	vis[0][0]=1;
	dis[0][0]=1;
	Q.push(node);
	while(!Q.empty())
	{
		cout<<1;
		d frist=Q.front();
		Q.pop();
		for(int i=0;i<4;i++)
		{
			int x=frist.x+dir[i][0];
			int y=frist.y+dir[i][1];
			
			if((x>=0)&&(x<n)&&(y>=0)&&(y<m)&&(!vis[x][y])&&mp[x][y]==1)
			{
				d node;
				node.x=x;
				node.y=y;
				node.step=frist.step+1;
				dis[x][y]=frist.step+1;
				vis[x][y]=1;
				cout<<x<<" "<<y<<" "<<node.step<<endl;
				Q.push(node);
			}
		 } 
	}
}
int main()
{
	for(int i=0;i<21;i++)
	{
		string str;
		cin>>str;
	
		for(int j=0;j<str.length();j++)
		{
			
			if(str[j]=='.')
			mp[i][j]=1;
			else{
				mp[i][j]=1;
			}
		}
	}
	bfs();
	cout<<dis[n-1][m-1]<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值