广度优先搜索的学习

19 篇文章 1 订阅
11 篇文章 0 订阅

同样也是用一个迷宫的例子

#include<iostream>
using namespace std;
struct note
{
	int x;//横坐标
	int y;//纵坐标
	int s;//步数
};
int main() {
	struct note que[2501];//设地图50X50,所以队列2500
	int a[51][51] = { 0 };//地图
	int book[51][51] = { 0 };//标记哪些点走过了
	int next[4][2] = {
		{0,1},//右
		{1,0},//下
		{0,-1},//左
		{-1,0}//上
	};
	int head, tail,flag;
	int next_x, next_y;
	int n,m,start_x,start_y,p,q;
	cout << "输入行和列" << endl;
	cin >> n >> m;
	cout << "输入迷宫" << endl;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			cin >> a[i][j];
	cout << "输入起点坐标" << endl;
	cin >> start_x >> start_y;
	cout << "输入终点坐标" << endl;
	cin >> p >> q;
	head = 1;//队列初始化
	tail = 1;
	que[tail].x = start_x;
	que[tail].y = start_y;
	que[tail].s = 0;
	tail++;
	book[start_x][start_y] = 1;
	flag = 0;//标记是否到达,1为到达
	while (head<tail)
	{
		for (int i = 0; i < 4; i++) {
			next_x = que[head].x + next[i][0];//顺时针方向,上下左右
			next_y = que[head].y + next[i][1];
			if (next_x<1 || next_x>n || next_y<1 || next_y>m)//判断越界
				continue;
			if (a[next_x][next_y] == 0 && book[next_x][next_y] == 0) {//判断是否可走
				book[next_x][next_y] = 1;//宽度遍历只要入队一次,所以不需要将book还原
				que[tail].x = next_x;
				que[tail].y = next_y;
				que[tail].s = que[head].s + 1;
				tail++;
			}
			if (next_x == p&&next_y == q) {//判断到达
				flag = 1;
				break;
			}
		}
		if (flag == 1)
			break;
		head++;//当一个点扩展结束后,head++才能对下一个点扩展
	}
	cout << que[tail - 1].s << endl;//tail是指向队尾的下一个位置,所以要减一
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值