标签:
本文使用BFS广度优先搜索算法实现求解迷宫的最短路径(C++),使用到了队列先进先出的性质,依次搜索路径直到找到目标出口(如果迷宫能走通)求解到的路径即为该迷宫的最短路径,找到返回true,找不到返回false,本文使用vexmap一个map容器记录队列的搜索路径(记录队列路径的实现有点草率,可以再优化)。</p><p> </p><pre class="cpp" name="code">#include<iostream>
#include<queue>
using namespace std;
typedef unsigned long long iUINT64;
map<iUINT64,int> vexmap;
const int g_errNUM = 88888;
offsets myMove4[4] = {//各个方向的偏移表
{-1,0,"N"},
{0,1,"E"},
{1,0,"S"},
{0,-1,"W"},
};
class Itmes
{
public:
iUINT64 x,y;//偏移量x,y和试探方向
Itmes():x(g_errNUM),y(g_errNUM)
{
}
};
bool BFS(Itmes star,Itmes end,int& cntNum)
{
cntNum = 0;
iUINT64 curx,cury,searchx,searchy;
queue<Itmes> ItemQ;
ItemQ.push(star);
iUINT64 Star = star.x << 32 | star.y;
vexMap[Star] = g_errNUM;
mark[star.x][star.y] = 1;
while (!ItemQ.empty())
{
Itmes tmp = ItemQ.front();
curx = tmp.x; cury = tmp.y;
ItemQ.pop();
for (int i = 0; i < 4; i++)
{
searchx = curx + myMove4[i].a;
searchy = cury + myMove4[i].b;
if (Maze[searchx][searchy] == 0 && mark[searchx][searchy] == 0)
{
mark[searchx][searchy] = 1;
Itmes tmp2;
tmp2.x = searchx;
tmp2.y = searchy;
iUINT64 NodeCur = curx << 32 | cury;
iUINT64 NodeSearch = searchx << 32 | searchy;
vexMap[NodeSearch] = NodeCur;
ItemQ.push(tmp2);
//出口条件
if (searchx == end.x && searchy == end.y)
{
iUINT64 Index = searchx << 32 | searchy;
while (vexMap[Index] != g_errNUM)
{
Index = vexMap[Index];
cntNum++;
if (cntNum > 1000000)//防护防止出现死循环,可优化
{
return false;
}
}
return true;
}
}
}
}
return false;
}
标签:
原文地址:http://www.cnblogs.com/ykc-lin/p/5020544.html