迷宫问题可以用递归的方式求解,在一个位置需要分别探索他的上下左右,然后到下一个位置再去探索,如果有多条路径,就要去遍历每一条,同时找到最短的一条。
我造了这样的一个迷宫如下图;其中 1是墙 0是通路
代码如下
#include <iostream>
#include <stack>
#include <windows.h>
#pragma warning(disable :4996)
using namespace std;
struct pos
{
int row;
int col;
};
template <int M,int N>
class Maze
{
public:
Maze(int* maze)
{
for (size_t i = 0; i < M; i++)
{
for (size_t j = 0; j < N; j++)
_maze[i][j] = maze[i*N+j];
}
}
~Maze()
{}
void Showmaze()
{
for (size_t i = 0; i < M; i++)
{
for (size_t j = 0; j < N; j++)
{
printf("%3d", _maze[i][j]);
}
cout << endl;
}
}
void GetShortPath(pos cur, stack<pos>&path, stack<pos>&shortpath)
{
if (path.empty())
{
path.push(cur);
_maze[cur.row][cur.col] = 2; //起点的话赋值2
}
else
{ //起点之后的位置每次比上个位置多1,就算遇到走过的路也可继续走下去
_maze[cur.row][cur.col] = _maze[path.top().row][path.top().col] + 1;
path.push(cur);
}
//判断出口同时判断是否为最短路径
if (cur.row == M - 1)
{
printf("找到了一个出口:a(%d,%d)\n",cur.row,cur.col);
if (shortpath.empty() || shortpath.size() > path.size())
{
shortpath = path;
path.pop();
return;
}
}
pos next = cur;
//向 上 探索
next.row -= 1;
if (CheckAccess(cur, next))
{
GetShortPath(next, path, shortpath);
}
next = cur;
//右
next.col += 1;
if (CheckAccess(cur, next))
{
GetShortPath(next, path, shortpath);
}
next = cur;
//下
next.row += 1;
if (CheckAccess(cur, next))
{
GetShortPath(next, path, shortpath);
}
next = cur;
//左
next.col -= 1;
if (CheckAccess(cur, next))
{
GetShortPath(next, path, shortpath);
}
next = cur;
if (!path.empty())
path.pop();
return;
}
//判断是否可以走这个位置
bool CheckAccess(pos cur, pos next)
{
if (cur.row >= 0 && cur.row < M&&cur.col >= 0 && cur.col < N)
{
if (_maze[next.row][next.col] == 0 || _maze[cur.row][cur.col] < _maze[next.row][next.col])
return true;
}
return false;
}
protected:
int _maze[M][N];
};
int main()
{
int a[10][10] = {
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }
};
Maze<10,10> maze((int*)a);
maze.Showmaze();
stack<pos> path, shortpath;
pos entry = { 2, 0 };
maze.GetShortPath(entry,path,shortpath);
maze.Showmaze();
printf("最短步数是 %d\n",shortpath.size());
system("pause");
return 0;
}
结果如下,1是墙1其他数字为走过的顺序