老鼠走迷宫抽象版c++

# ifndef MAZE_H
# define MAZE_H
# include<iostream>
# include"stack.h"
using namespace std;
class position{
	public:
		int x;
		int y;
};
stack<position> *path;
class Maze
 {
	public:
	void welcom();
	void inputmaze();
	bool findpath();
	void outputmaze();
	protected:
	int **maze;
	int n;
};
void Maze::welcom()
{
	cout<<"请输入迷宫矩阵的大小:"<<endl;
	cin>>n;
}
void Maze::inputmaze()
{
	maze=new int *[n+2];
	for(int i=0;i<n+2;i++)
	  maze[i]=new int [n+2];
	  //以上为动态分配数组空间
	for(int i=0;i<=n+1;i++)
	 {
	 maze[i][0]=1;
	 maze[i][n+1]=1;
	 maze[0][i]=1;
	 maze[n+1][i]=1;
     }
     //以上为在迷宫周围立上围墙
	 cout<<"输入迷宫矩阵"<<endl;
	 for(int i=1;i<=n;i++)
	 for(int j=1;j<=n;j++)
	   cin>>maze[i][j];
}
//以下为核心代码,以深度优先搜索为代码思想
bool Maze::findpath()
{
  path=new stack<position>;
  position offset[4];
  offset[0].x=1;offset[0].y=0;//right
  offset[1].x=0;offset[1].y=1;//down
  offset[2].x=-1;offset[2].y=0;//left
  offset[3].x=0;offset[3].y=-1;//up
  position here;
  here.x=1;
  here.y=1;
  maze[1][1]=2;//起点做标记 
  int option=0;
  int lastoption=3;
  while(here.x!=n||here.y!=n)
  {
  	int r,c;
  	while(option<=lastoption)
  	{
  		r=here.x+offset[option].x;
  		c=here.y+offset[option].y;
  		if(maze[c][r]==0)
  		   break;
  		option++;
	  }
  	if(option<=lastoption)
  	  {
  		path->push(here);
  		here.x=r;
  		here.y=c;
  		maze[c][r]=2;//走过的点做标记
  		option=0;
	   }
  	else{
  		if(path->empty())
  		  return false;
  		position next=path->Top();
  		path->pop();
  		if(here.y==next.y)
  		   option=2+next.x-here.x;
  		else
  		  option=3+next.y-here.y;
  		  maze[here.y][here.x]=-1;//走不通,去掉标记。
  		  here=next;
	  }
    }
    return true;
}
void Maze::outputmaze()
{
	position here;
	if(findpath())
	{
		for(int i=0;i<=n+1;i++)
		{
		 for(int j=0;j<=n+1;j++)
		  { 
		   if(maze[i][j]==1)
		   cout<<'#';
		   if(maze[i][j]==2)
		   cout<<'*';
		   if(maze[i][j]==-1||maze[i][j]==0)
		    cout<<" ";
		  }
		  cout<<endl;
	   }
	}
    else cout<<"没有路径"<<endl; 
 } 
# endif 
# include<iostream>
# include"maze.h"
using namespace std;
int main()
{
	Maze s;
	s.welcom();
	s.inputmaze();
	s.outputmaze();
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值