前面我们写到迷宫的普通版,那这篇文章就来写一下如何用递归来实现!
递归实现迷宫问题同普通版差不多,其中关键思路、初始化及打印地图、创建位置结点类等与普通版一样,只有判断坐标的合理性与寻找迷宫通路的方法不同而已。
源代码如下:
#include <iostream>
#include <assert.h>
using namespace std;
#include <stack>
#pragma warning(disable:4996)
const size_t N = 10;
void InitMaze(int maze[][N], size_t N) //初始化迷宫图
{
FILE* fout = fopen("Maze.txt","r");
assert(fout);
for(size_t i=0; i<N; ++i)
{
for(size_t j=0; j<N; )
{
//获得迷宫图上坐标的ASCII值
char ch = fgetc(fout);
if((ch == '0') || (ch == '1'))
{
maze[i][j] = ch - '0';
++j;
}
}
}
}
void PrintMaze(int maze[][N], size_t N) //打印迷宫图
{
for(size_t i=0; i<N; ++i)
{
for(size_t j=0; j<N; ++j)
{
cout<<maze[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
struct Pos //定义位置结点
{
size_t _row; //行
size_t _col; //列
};
bool CheckAccess(int maze[][N], size_t N, Pos pos) //判断坐标的位置是否合理
{
if(((pos._row>=0) && (pos._row<N))
&& ((pos._col>=0) && (pos._col<N))
&& (maze[pos._row][pos._col] == 0))
{
return true;
}
return false;
}
//运用递归
bool GetMazePathR(int maze[][N], size_t N, Pos cur)
{
maze[cur._row][cur._col] = 2; //将已走过的位置赋值为2
Pos next;
//上
next = cur;
next._row--;
if(CheckAccess(maze, N, next))
{
if(GetMazePathR(maze, N, next))
{
return true;
}
}
//右
next = cur;
next._col++;
if(CheckAccess(maze, N, next))
{
if(GetMazePathR(maze, N, next))
{
return true;
}
}
//下
next = cur;
next._row++;
if(CheckAccess(maze, N, next))
{
if(GetMazePathR(maze, N, next))
{
return true;
}
}
//左
next = cur;
next._col--;
if(CheckAccess(maze, N, next))
{
if(GetMazePathR(maze, N, next))
{
return true;
}
}
return false;
}
void TestMaze()
{
int maze[N][N];
InitMaze(maze, N);
PrintMaze(maze, N);
Pos entry;
entry._row = 2;
entry._col = 0;
GetMazePathR(maze, N, entry);
PrintMaze(maze, N);
}
int main()
{
TestMaze();
system("pause");
return 0;
}
我们打印迷宫地图时,采用了文件的方式,如果有志同道合的人看到了这篇文章,想要动手操作一下的话,需要编写一份文本文件Maze.txt,并将它加载到项目的文件夹中。
下图为样例。