⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 迷宫.cpp

📁 自己用C++做的简单的迷宫
💻 CPP
字号:
#include<iostream.h>
#include<stdlib.h>
#define MAXROW 100
#define MAXCOL 100

struct stack_node
{
	int x,y;
	struct stack_node *next;
};

typedef struct stack_node stack_list;
typedef stack_list *link;
link path=NULL;
//创建迷宫
void createmaze(int maze[MAXROW][MAXCOL],int row,int col )
{
	int i,j;
	for(i=0;i<row;i++)
	{
		for(j=0;j<col;j++)
		{
			if(j==0||j==col-1)
				maze[i][j]=1;
		}
	}
	for(j=0;j<col;j++)
	{
		for(i=0;i<row;i++)
		{
			if(i==0||i==row-1)
				maze[i][j]=1;
		}
	}
	cout<<"================================="<<endl;
	cout<<endl<<"创建迷宫,";
	cout<<"请输入"<<row-2<<"*"<<col-2<<"大小的迷宫"<<endl;
	for(i=1;i<=row-2;i++)
	{
		for(j=1;j<=col-2;j++)
		{
			cin>>maze[i][j];
		}
	}
	cout<<endl;
	cout<<"迷宫图为:"<<endl;
	for(i=0;i<row;i++)
	{
		for(j=0;j<col;j++)
		{
			cout<<maze[i][j]<<"  ";
		}
		cout<<endl;
	}
}
//栈数据的存入
link push(link stack,int x,int y)
{
	link newnode;
	newnode=(link)malloc(sizeof(stack_list));
	if(!newnode)
	{
		cout<<"内存分配失败!";
		return NULL;
	}
	newnode->x=x;
	newnode->y=y;
	newnode->next=stack;
	stack=newnode;
	return stack;
}

//栈数据的取出
link pop(link stack,int *x,int *y)
{
	link top;
	if(stack!=NULL)
	{
		top=stack;
		stack=stack->next;
		*x=stack->x;
		*y=stack->y;
		delete top;
		return stack;
	}
	else *x=-1;
}

void main()
{		
	cout<<endl<<endl<<"==========================="<<endl;
	cout<<"0表示通路"<<endl;
	cout<<"1表示墙壁"<<endl;
	cout<<"2表示走过的路"<<endl;
	cout<<"3表示回溯的路"<<endl;
	cout<<"搜索方向下-〉右-〉上-〉左"<<endl;
	cout<<"==========================="<<endl;
	int maze[MAXROW][MAXCOL];
	int row,col;
	cout<<"请输入迷宫行数和列数(迷宫最外面一层为墙壁):";
	cin>>row>>col;
	createmaze(maze,row,col);
	int i,j;
	int x,y;
	int m,n;
	cout<<"请输入迷宫的入口坐标:";
	cin>>x>>y;
	cout<<"请输入迷宫的出口坐标:";
	cin>>m>>n;
	while(x!=m||y!=n)
	{
		maze[x][y]=2;
		if(maze[x+1][y]<=0)                 //下
		{
			x=x+1;
			path=push(path,x,y);
		}
		else
			if(maze[x][y+1]<=0)               //右
			{
				y=y+1;
				path=push(path,x,y);
			}
			else
				if(maze[x-1][y]<=0)           //上
				{
					x=x-1;
					path=push(path,x,y);
				}
				else
					if(maze[x][y-1]<=0)         //左
					{
						y=y-1;
						path=push(path,x,y);
					}
					else
					{
						maze[x][y]=3;
						path=pop(path,&x,&y);
					}
	}
	maze[x][y]=2;
	cout<<"迷宫途径如下所视:"<<endl;
	for(i=1;i<row-1;i++)
	{
		for(j=1;j<col-1;j++)
		{
			cout<<maze[i][j]<<"  ";
		}
		cout<<endl;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -