?講解:
一、采用二維數(shù)組和srand函數(shù)隨機生成只有0和1的迷宮。
二、求解迷宮大概思路:先將入口處的坐標即方向d入棧,然后當棧不為空時,取出棧頂(即當前節(jié)點)的數(shù)據(jù)。遍歷當前節(jié)點的四個方向,找到可行的下一個節(jié)點,并將其入棧;如沒有可行的下一個節(jié)點,則將當前節(jié)點值0(表示未走過),然后出棧,退回到前一個節(jié)點進行遍歷。當棧頂數(shù)據(jù)和出口一致時,輸出迷宮的通路。
#include <iostream>
#include <time.h>
#define M 100
#define N 100
#define MAXSIZE 100
using namespace std;
int maze[M][N];
void CreateMaze(int m, int n) //創(chuàng)建迷宮
{
srand(time(NULL));
for(int i=1;i<m+1;i++)
{
for(int j=1;j<n+1;j++)
{
maze[i][j] = rand()%2; //只有0和1的隨機迷宮
}
}
maze[1][1] = -1; //直接入口置-1,表示可走
maze[m][n] = 0; //出口
for(int i=0;i<m+2;i++) maze[i][0] = 1; //設置圍墻
for(int i=0;i<m+2;i++) maze[i][m+1] = 1;
for(int j=0;j<n+2;j++) maze[0][j] = 1;
for(int j=0;j<n+2;j++) maze[n+1][j] = 1;
}
void Print(int m,int n) //打印迷宮
{
for(int i=0;i<m+2;i++)
{
for(int j=0;j<n+2;j++)
{
if(maze[i][j] == 0)
cout << " ";
if(maze[i][j] == 1)
cout << "□";
}
cout << endl;
}
}
typedef struct //定義當前位置坐標
{
int x;
int y;
int d; //移動方向
}Point;
typedef struct //定義順序棧
{
Point data[MAXSIZE]; //定義順序棧的存儲類型為結(jié)構(gòu)體data
int top;
}SqStack;
bool MazePath(int x1,int y1,int m, int n)
{
int i,j,d,find;
SqStack S;
S.top = -1; //初始化棧
S.top++;
S.data[S.top].x = x1; S.data[S.top].y = y1; S.data[S.top].d = -1;
while(S.top>-1)
{
i = S.data[S.top].x; j = S.data[S.top].y; d = S.data[S.top].d;
if(i==m&&j==n)
{
cout << "找到路徑:" << endl;
for(int i=0;i<m+2;i++)
{
for(int j=0;j<n+2;j++)
{
if(maze[i][j] == 1)
cout << "□";
else if(maze[i][j] == 0)
cout << " ";
else
cout << " *";
}
cout << endl;
}
return true;
}
find = 0; //設置標識,1表示找到下一個可行路徑,0表示沒有找到
while(d<4&&find==0) //遍歷4個方向:0->東,1->南,2->西,3->北
{
d++;
switch(d)
{
case 0:
i = S.data[S.top].x+1; j = S.data[S.top].y; break;
case 1:
i = S.data[S.top].x; j = S.data[S.top].y+1; break;
case 2:
i = S.data[S.top].x-1; j = S.data[S.top].y; break;
case 3:
i = S.data[S.top].x; j = S.data[S.top].y-1; break;
}
if(maze[i][j] == 0) find = 1; //找到路徑,標識置1,退出循環(huán)
}
if(find == 1) //找到路徑
{
S.data[S.top].d = d; //記錄當前節(jié)點往下一個節(jié)點的方向
S.top++; //下一個節(jié)點入棧
S.data[S.top].x = i;
S.data[S.top].y = j;
S.data[S.top].d = -1; //將下一個節(jié)點的走向置為-1
maze[i][j] = -1; //當前點置-1,表示走過
}
else //未找到路徑
{
maze[S.data[S.top].x][S.data[S.top].y] = 0; //當前點置為0,表示未走過
S.top--; //出棧
}
}
return false;
}
int main()
{
int m,n;
int k=1;
while(k)
{
cin >> m >> n;
CreateMaze(m,n);
Print(m,n);
if(!MazePath(1,1,m,n))
{
cout << "找不到路徑"<<endl;
k++;
}
else k=0;
}
}
運行結(jié)果:(由于隨機生成大概率沒有通路,所以輸出較小的迷宮容易出結(jié)果)
?文章來源:http://www.zghlxwxcb.cn/news/detail-541832.html
?寫的很簡陋,有不足之處請指正。文章來源地址http://www.zghlxwxcb.cn/news/detail-541832.html
到了這里,關于數(shù)據(jù)結(jié)構(gòu)——迷宮問題(順序棧、C++)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!