广度优先算法的实现(BFS)

`
``

#include
#include
using namespace std;

//定义点的结构体
struct temp
{
int x;
int y;
};

struct Way{
temp tp;
int index;

};

int main(){
int m;
int n;
cout << “输入要找到的数字的下标(4行5列数组)” << endl;
cin >> m >> n;
if (m > 3 || n > 4)
{
cout << “超出了限制值” << endl;
return 0;
}

//地图
int a[4][5] = {
	{ 1, 2, 3, 4, 5 },
	{ 6, 7, 8, 9, 10 },
	{ 11, 12, 13, 14, 15 },
	{ 16, 17, 18, 19, 20 }
};

//定义一个bool型的数组判断是否走过这条路
bool b[4][5] = {
	{ true, true, true, true, true },
	{ true, true, true, true, true },
	{ true, true, true, true, true },
	{ true, true, true, true, true }
};
vector<Way> v1;	//用来存放元素
vector<Way> path;//用来存放路径
int i = 0;
int j = 0;
int count =-1;
bool p = true;
//把a[0][0]先入队
temp t = { i, j };
Way w = { t, -1 };
b[i][j] = false;
v1.push_back(w);

while ((i != m || j != n) || (v1.empty()))//找到了或者是队列中已经没有元素了
{
	count++;
	i = v1[count].tp.x;
	j = v1[count].tp.y;
	//向上走
	if (i != 0 &&(b[i - 1][j] != false))//上
	{
		temp t = { i-1, j };
		Way w = { t, count };
		b[i-1][j] = false;
		v1.push_back(w);
	}

	//下
	if (i != 3 && (b[i + 1][j] != false))//下
	{
		temp t = { i+1, j };
		Way w = { t, count };
		b[i + 1][j] = false;
		v1.push_back(w);
	}

	//左
	if (j != 0 && (b[i ][j-1] != false))//左
	{
		temp t = { i, j-1 };
		Way w = { t, count };
		b[i][j-1] = false;
		v1.push_back(w);
	}

	//右
	if (j != 4 && (b[i][j+1] != false))//右
	{
		temp t = { i, j+1 };
		Way w = { t, count };
		b[i][j+1] = false;
		v1.push_back(w);
	}	
}

while (count>=0)
{
	path.push_back(v1[count]);
	count = v1[count].index;
}

for (int i = path.size()-1; i >= 0; i--)
{
	cout <<"("<< path[i].tp.x <<","<< path[i].tp.y<<")"<< endl;
}



return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值