BFS广搜解决迷宫问题

例题:

 代码:(好好看注释)

//BFS广搜解决迷宫问题 
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
using namespace std;
typedef long long ll;
const int N=1024;
/*5 4 
	1 1 2 1 
	1 1 1 1
	1 1 2 1 
	1 2 1 1 
	1 1 1 2
1 1 4 3案例 */
int dx[4]={0,0,1,-1};//四个方向 
int dy[4]={1,-1,0,0};
int a[N][N],v[N][N];//a是原数组,v是访问数组 
struct point{//为了存坐标和走了的步数,开一个结构体和队列 
	int x;
	int y;
	int step;
};
queue<point> r;//申请队列 
int main()
{
	//输入 
	int n,m;
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			scanf("%d",&a[i][j]);
		}
	}
	int startx,starty,p,q;//起点坐标和终点坐标
	scanf("%d %d %d %d",&startx,&starty,&p,&q);
	 //BFS 
	point start;
	start.x=startx;
	start.y=starty;
	start.step=0;
	r.push(start);//将起点入队 
	v[startx][starty]=1;//起点已经访问
	int flag=0;
	while(!r.empty()){//不要忘了括号 ,这是条件 
		int x=r.front().x;
		int y=r.front().y;
		if(x==p&&y==q){
			flag=1;
			printf("%d",r.front().step);
			break;
		}
		for(int k=0;k<=3;k++){
			int tx=x+dx[k];
			int ty=y+dy[k];
			if(a[tx][ty]==1&&v[tx][ty]==0){//坐标(tx,ty)是空地,即没有障碍物&&没有被访问
				   //入队
				    point temp;
				    temp.x=tx;
				    temp.y=ty;
				    temp.step=r.front().step+1;
				    r.push(temp);
				    v[tx][ty]=1;
			} 
		}
		r.pop();//拓展完了需要将队首元素出队  
	}
	 if(flag==0)  printf("NO");
	return 0;
}

运行结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值