实验要求
实验的要求是生成一个迷宫,然后找出迷宫从入口到出口的路径
,考察了学生的数据结构编辑能力和递归非递归的
实现能力。 迷宫问题每走一步要看到后面几步,遇到死胡同及时回头,重新寻找出路。计算机术语称为回溯,而实
现回溯的方法有:递归方式和非递归方式。
本实验设计的迷宫问题应该包含以下功能:
(1)迷宫大小可以定义
(2)迷宫入口默认为左上角,出口默认为右下角(也可自定义
(3)给出迷宫的生成和求解过程
代码
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<cstring>
using namespace std;
const int size=100;
int m,n;
int mg[size][size];
struct node
{
int x,y;
node(){}
node(int x,int y)
{
this->x = x;
this->y = y;
}
};
int vis[size][size];
node son[size][size];
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
void make_map()
{
srand(time(NULL));
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
int x = rand()%3; //0 1 2 3
if(x != 0)
mg[i][j] = 0;
else
mg[i][j] = 1;
}
mg[n-1][m-1] = mg[0][0] = 0;
memset(vis,0,sizeof(vis));
return ;
}
bool judge(int x,int y)
{
if(x<0||x>=n||y<0||y>=m||vis[x][y]==1||mg[x][y]==1)
return false;
else
return true;
}
bool dfs(int x,int y)
{
if(x==n-1&&y==m-1)
return true;
for(int i=0;i<4;i++)
{
int xx = x+dir[i][0];
int yy = y+dir[i][1];
node temp = node(xx,yy);
if(judge(xx,yy))
{
vis[xx][yy] = 1;
if(dfs(xx,yy))
{
son[x][y] = temp;
return true;
}
vis[xx][yy] = 0;
}
}
return false;
}
int main()
{
cin>>m>>n;
make_map();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cout<<mg[i][j]<<' ';
cout<<endl;
}
if(dfs(0,0))
{
node temp = node(0,0);
while(temp.x!=n-1||temp.y!=m-1)
{
printf("(%d,%d)\n",temp.x+1,temp.y+1);
temp = son[temp.x][temp.y];
}
printf("(%d,%d)\n",temp.x+1,temp.y+1);
}
else
printf("mdl!\n");
}