前面有使用深度优先算法来解迷宫问题,思路是使用递归的方法,先进行深度的尝试,找到或者无法抵达时返回上一级函数继续执行。
本文使用广度优先算法,思路如下:如图在(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);
}