简易迷宫--递归算法实现

#include<iostream>
#include<stack>
using namespace std;

#define MaxCol 10
#define MaxRow 10

struct Seat//定义一个表示位置的结构体
{
	Seat(int x,int y)
		:_x(x)
		,_y(y)
	{}
	int _x;
	int _y;
};
class Maze
{
public:
	Maze(int arr[][MaxCol], int Row, int Col)
	{
		_map = new int*[MaxRow];//先开辟行的空间
		for(int i = 0; i < MaxRow; ++i)
		{
			_map[i] = new int[MaxCol];//再在每行开辟列的空间
			for(int j = 0; j < MaxCol; j++)
			{
				_map[i][j] = arr[i][j];
			}
		}
	}

	void PrintMaze()//打印迷宫
	{
		for(int i = 0;i < MaxRow;i++)
		{
			for(int j = 0;j < MaxCol;j++)
			{
				cout<<_map[i][j]<<" ";
			}
			cout<<endl;
		}
		cout<<endl;
	}

	~Maze()
	{
		for(int i = 0; i < MaxCol; ++i)//先销毁每行中开辟的空间
		{
			delete[] _map[i];
		}
		delete _map;
	}

	bool IsPass(Seat s)//判断当前位置是否为通路
	{
		if(1 == _map[s._x][s._y])
			return true;

		if(s._x < 0 || s._x >= MaxRow || s._y < 0 || s._y >= MaxCol)//出口
			return true;

		return false;
	}

	bool PassMaze(Seat& s)//走迷宫
	{
		if(s._x < 0 || s._x >= MaxRow || s._y < 0 || s._y >= MaxCol)//防止数组越界
			return true;

		if(IsPass(s))//若当前位置为通路
		{
			_map[s._x][s._y] = 2;//标记当前走过的位置为2
			//将当前位置前后左右坐标给出
			Seat front(s._x-1,s._y);
			Seat left(s._x, s._y-1);
			Seat right(s._x, s._y+1);
			Seat down(s._x+1, s._y);

			if(PassMaze(front))//利用递归来探路
			{
				_map[s._x][s._y] = 2;
				return true;
			}
			if(PassMaze(left))
			{
				_map[s._x][s._y] = 2;
				return true;
			}
			if(PassMaze(right))
			{
				_map[s._x][s._y] = 2;
				return true;
			}
			if(PassMaze(down))
			{
				_map[s._x][s._y] = 2;
				return true;
			}
			_map[s._x][s._y] = 3;//若前后左右都走不通则回退回来并且将原来位置标记为3,防止走回头路
			return false;
		}

	}
private:
	int **_map;//定义一个二级指针存储二维数组
};

int main()
{
	int MapArr[MaxRow][MaxCol] = {
		{0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 1, 1, 1, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
		{1, 0, 1, 0, 1, 0, 0, 0, 0, 0},
		{0, 0, 1, 0, 1, 0, 0, 0, 0, 0},
		{0, 0, 1, 1, 1, 0, 0, 0, 0, 0},
		{0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 1, 1, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 1, 0, 0, 0}};
		Maze maze(MapArr,MaxRow,MaxCol);
		maze.PrintMaze();
		Seat s(9,6);//给出入口
		maze.PassMaze(s);//走迷宫
		maze.PrintMaze();//将走过的路线打印出来

	system("pause");
	return 0;
}

附上结果截图


其实在走迷宫那部分中的递归回溯算法就是一种探路的思想,看前后左右哪个节点可以走通。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值