简单迷宫的实现-------------找一条通路

#include<iostream>
#include<assert.h>
#include<stack>
using namespace std;
//求解路径的基本思想:1.如果当前路径能够通过,将当前路经进行压栈,为了回退(回溯法),并将走过的路标记成2  不能走1,0可以走
//2.如果当前路径上下左右都不能通过,则出栈(回溯)并且将当前路径标为3  即将回溯路径标记为3
//3.栈为空(表示回到起点)也表示没有出路
#define  M 10
#define N 10
class Maze
{
public://内部类,作用域在maze类中

	 struct Pos
	{
		size_t _row;
		size_t _col;
		
	};
	 typedef struct Pos Pos;
	Maze(int maze[M][N])//初始化迷宫
	{
		for (size_t i = 0; i < M; i++)
		{
			for (size_t j = 0; j < N; j++)
			{
				_maze[i][j] = maze[i][j];
				//_maze[i][j]=maze[i*N+j];二维数组其实是按一维数组的顺序排列的
			}
		}
	}
	bool CheckAccess(Pos next)
	{
		if ((next._row >= 0) && (next._row < M) && (next._col >= 0) && (next._col < N)&&(_maze[next._row][next._col]==0))
		{
			return true;
		}
		return false;
	}
	bool GetMazePath(Pos entry)
	{
		stack<Pos> paths;
	    paths.push(entry);
		_maze[entry._row][entry._col] = 2;//走过的路标记为2
		while (!paths.empty())//如果栈为空,就表示找不到出口
		{  //栈顶的坐标,就是当前位置
			Pos cur = paths.top();
			//试探四个方向
			
			if (((cur._row == M - 1) || (cur._col == N- 1))&& ((cur._col!=entry._col)&&(cur._row!=entry._row)))
			{
				return false;
			}
			
			//上
			 Pos next = cur;
			next = cur;
			next._row += 1;
			if (CheckAccess(next))
			{
				paths.push(next);
				_maze[next._row][next._col] = 2;
				continue;

			}
			//下
			 next = cur;
			next._row -= 1;
			if (CheckAccess(next))
			{
				paths.push(next);
				_maze[next._row][next._col] = 2;
				continue;
			}
			//左
			next = cur;
			next._col -= 1;
			if (CheckAccess(next))
			{
				paths.push(next);
				_maze[next._row][next._col] = 2;
				continue;
			}
			
			//右
			next = cur;
			next._col += 1;
			if (CheckAccess(next))
			{
				paths.push(next);
				_maze[next._row][next._col] = 2;
				continue;
			}
			
			
			
			//走到此处说明next位置,四个方向都走不通    回溯
			Pos back = paths.top(); // 将走不通的标记为3,即将回溯的路记为3
			_maze[back._row][back._col] = 3;
			paths.pop();
			

		}
		return false;
	}

	void print()
	{
		for (size_t i = 0; i < M; i++)
		{
			for (size_t j = 0; j < N; j++)
			{
				cout << _maze[i][j] << " ";
			}
			cout << endl;
		}
		cout << endl;
	}
	
protected:
	int _maze[M][N];

};
void Test()
{

	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, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 0, 0, 0, 0, 0, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 0, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 0, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 0, 1, 1, 1,
		1, 1, 0, 0, 1, 1, 0, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 0, 1, 1, 1
	};
	Maze m(a);
	m.print();
	Maze::Pos entry;
	entry._row = 2;
	entry._col = 0;
	m.GetMazePath(entry);
	m.print();
}


我的生物钟调不过来了,下午困,晚上睡不着。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值