bfs广度优先迷宫,最短路径

#include <iostream>
#include <queue>
using namespace std;

//定义一个点,分别表示x,y点,和已经走的步数
struct point
{
	int x, y, dis;
};

//表示方向
int xx[4] = { 1,-1,0,0 },yy[4] = { 0,0,1,-1 };

int bfs(int x, int y, int a, int b, int maze[][7])
{
	queue<point> myque;
	point pt;
	pt.x = x, pt.y = y, pt.dis = 0;
	myque.push(pt);
	while (!myque.empty())
	{
		pt = myque.front();
		myque.pop();
		
		//判断是否到达目标并返回走的步数,保证是最短路径
		if (pt.x == a && pt.y == b)
		{
			return	pt.dis;
		}
		
		//判断该点四个方向是否可以走,如果可以的话就进栈
		for (int i = 0; i < 4; i++)
		{
			if (pt.x + xx[i] >= 0 && pt.x + xx[i] < 7 && 
				pt.y + yy[i] >= 0 && pt.y + yy[i] < 7 && 
				maze[pt.x + xx[i]][pt.y + yy[i]] == 0)
			{
				point temp;
				temp.x=pt.x + xx[i];
				temp.y=pt.y + yy[i];
				temp.dis=pt.dis+1;
				maze[pt.x][pt.y] = 1;
				myque.push(temp);
			}
		}
	}
}

int main()
{
		int maze[7][7] =
		{ 
			{1, 1, 1, 1, 1, 1, 1},
			{1, 0, 0, 0, 0, 0, 1},
			{1, 1, 0, 1, 0, 1, 1},
			{1, 0, 0, 1, 1, 1, 1},
			{1, 0, 1, 0, 0, 0, 1},
			{1, 0, 0, 0, 1, 0, 1},
			{1, 1, 1, 1, 1, 1, 1}
		};
		int x, y, a, b;
		cin >> x >> y >> a >> b;
		cout<<bfs(x, y,a,b, maze) ;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值