随机地图c++生成求迷宫最短路径算法
最短路径解释参考
添加链接描述
代码
#include<iostream>
using namespace std;
#include<ctime>
int mg[12][12] =
{
{1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,0,0,1,0,0,0,0,0,1},
{1,1,1,0,1,1,0,0,0,0,0,1},
{1,0,1,0,0,0,0,0,0,0,0,1},
{1,0,0,1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,1,0,0,0,1},
{1,0,1,0,0,0,0,1,1,1,1,1},
{1,1,0,1,0,1,0,0,0,0,1,1},
{1,0,1,1,0,1,0,0,1,0,0,1},
{1,0,1,0,0,0,0,0,0,1,0,1},
{1,1,0,0,1,0,0,1,1,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1}
};//数组存贮地图,四周加一道围墙
typedef struct
{
int i, j;
int pre;
}Box;//方块类型
typedef struct
{
Box data[100];
int front, rear;
}QuTape;
void print(QuTape qu, int front);
void randompath(int m[12][12]) {
srand((unsigned)time(0));
for (int j = 0; j < 12; j++)
{
m[0][j] = 1;
m[11][j] = 1;
}
for (int j = 1; j < 11; j++)
{
m[j][0] = 1;
m[j][11] = 1;
}
for (int i = 1;i < 11; i++)
{
for (int j = 1; j < 11; j++)
{
m[i][j] =( rand() % 11) >= 4 ? 0: 1;
}
}
}
void showmg(int m[12][12])
{
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++)
{
cout << m[i][j];
}
cout << endl;
}
}
bool mgpath(int xi, int yi, int xe, int ye)
{
int i, j, find = 0, di;
QuTape qu;
qu.front = qu.rear = -1;
qu.rear++;
qu.data[qu.rear].i = xi;
qu.data[qu.rear].j = yi;
qu.data[qu.rear].pre = -1;
mg[xi][yi] = -1;
while (qu.front != qu.rear && !find)
{
qu.front++;
i = qu.data[qu.front].i;
j = qu.data[qu.front].j;
if (i == xe && j == ye)
{
find = 1;
print(qu, qu.front);
return true;
}
for (di = 0; di < 4; di++)
{
switch (di)
{
case 0:i = qu.data[qu.front].i - 1; j = qu.data[qu.front].j; break;
case 1:i = qu.data[qu.front].i; j = qu.data[qu.front].j + 1; break;
case 2:i = qu.data[qu.front].i + 1; j = qu.data[qu.front].j; break;
case 3:i = qu.data[qu.front].i; j = qu.data[qu.front].j - 1; break;
default:
break;
}
if (mg[i][j] == 0)
{
qu.rear++;
qu.data[qu.rear].i = i; qu.data[qu.rear].j = j;
qu.data[qu.rear].pre = qu.front;
mg[i][j] = -1;
}
}
}
return false;
}
void print(QuTape qu, int front)
{
int k = front, j, ns = 0;
cout << endl;
do
{
j = k;
k = qu.data[k].pre;
qu.data[j].pre = -1;
} while (k != 0);
cout << "迷宫路径如下我的可爱鬼:\n";
k = 0;
while (k < 100)
{
if (qu.data[k].pre == -1)
{
ns++;
cout << "(" << qu.data[k].i << "," << qu.data[k].j << ")";
if (ns % 5 == 0)
cout << endl;
}
k++;
}
cout << endl;
}
int main()
{
int q, w, e, r;
randompath(mg);
showmg(mg);
cout << "输入起点坐标,终点坐标的数字(输入一个数字后enter再输入第二个):";
cin >> q >> w >> e >> r;
if (!mgpath(q,w,e,r))
cout << "无解";
system("pause");
}