广度优先搜索算法解迷宫问题

前面有使用深度优先算法来解迷宫问题,思路是使用递归的方法,先进行深度的尝试,找到或者无法抵达时返回上一级函数继续执行。

本文使用广度优先算法,思路如下:如图在(1,1)的位置开始,广度优先算法的步骤是搜索一步能够抵达的所有位置作为第一层,然后在上一层的基础上再走一步,并且不走重复的格子,作为下一层,这样一层一层的搜索,达到终点再停止。

下面程序用广度搜索算法解决迷宫的问题,数据结构十分巧妙,同样可以获得12的结果。

#include <stdio.h>
using namespace std;

struct Position
{
	Position()
	{
		x = 0;
		y = 0;
		father = 0;
		step = 0;

	}
	Position(int row, int col)
	{
		x = row;
		y = col;
		father = 0;
		step = 0;
	}
	int x;//横坐标
	int y;//纵坐标
	int father;//父节点在队列中的编号
	int step;//步数
	Position& operator = (Position& p)
	{
		x = p.x;
		y = p.y;
		return *this;
	}
	bool operator == (Position& p)
	{
		return x == p.x && y == p.y;
	}
};

enum Direction
{
	Left,
	Right,
	Up,
	Down
};

Position NextPosition(Position pNow, Direction dMove)
{
	Position pTarget = pNow;
	switch (dMove)
	{
	case Left:
		pTarget.y--;
		break;
	case Right:
		pTarget.y++;
		break;
	case Up:
		pTarget.x--;
		break;
	case Down:
		pTarget.x++;
		break;
	default:
		break;
	}
	return pTarget;
}

const int ROW = 5;
const int COL = 4;
int MazeMap[ROW][COL] = {
	0,0,1,0,
	0,0,1,0,
	0,0,1,0,
	0,1,0,0,
	0,0,0,1
};
bool book[ROW][COL] = { false };

//广度优先算法
void bfs(Position p, int& iTotalStep)
{
	Position pQueue[ROW*COL];
	Position pEnd(0,3);
	int head = 0;
	int tail = 0;
	pQueue[head].x = p.x;
	pQueue[head].y = p.y;
	pQueue[head].father = head;
	pQueue[head].step = 0;
	book[p.x][p.y] = true;
	tail++;
	while (head < tail)
	{
		bool bFindTarget = false;
		for (int i=0; i<=Down; i++)
		{
			Position pTarget = NextPosition(pQueue[head], (Direction)i);
			if (pTarget.x <0 || pTarget.y <0 || pTarget.x >= ROW || pTarget.y >= COL)
			{
				continue;
			}
			if (!book[pTarget.x][pTarget.y] && MazeMap[pTarget.x][pTarget.y] == 0)
			{
				book[pTarget.x][pTarget.y] = true;
				pQueue[tail].x = pTarget.x;
				pQueue[tail].y = pTarget.y;
				pQueue[tail].father = head;
				pQueue[tail].step = pQueue[head].step + 1;
				tail++;
			}

			if (pTarget == pEnd)
			{
				bFindTarget = true;
				iTotalStep = pQueue[head].step + 1;
				break;
			}

		}
		if (bFindTarget)
		{
			break;
		}
		head++;		
	}
}


int main()
{
	Position pStart(0,1);
	int iSetp = 0;
	bfs(pStart, iSetp);

    printf("Shortest path length is %d.", iSetp);
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值