#include"\header1.h"
#define N 5
void makeprint(int map[][N],pos p) {
map[p.x][p.y] = 3;//不能走/死胡同标记为3
}
pos nexpos(pos curpos, int i) {//走的顺序:顺时针
switch (i) {
{
case 1:curpos.y++;
break;
case 2:curpos.x++;
break;
case 3:curpos.y–;
break;
case 4:curpos.x–;
break;
default:
break;
}
}
return curpos;
}
//足迹
void foot(int map[][N],pos curpos) {
map[curpos.x][curpos.y] = -1;//足迹,走过-1表示
}
//当前点是不是可以走
bool pass(int map[][N],pos curpos) {
if (map[curpos.x][curpos.y] == 0) {//为0表示可以走
return true;
}
else {
return false;
}
}
创建迷宫
void creat(int map[][N], int i, int j) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
map[i][j] = 0;
}
}
for (int m = 0; m < j; m++) {
map[0][m] = 1;
map[N - 1][m] = 1;
map[m][0] = 1;
map[m][N - 1] = 1;
}
map[1][3] = 1;
map[2][2] = 1;
}
//输出迷宫
void showmaze(int map[][N], int i, int j) {
for (int m = 0; m < N; m++) {
for (int n = 0; n < N; n++) {
printf("%d\t", map[m][n]);
}
printf("\n\n");
}
}
//迷宫路径走法
void maze(int map[][N], pos start, pos end) {
Stack L;
InitStack(L);
pos curpos = start;
do
{
//当前位置可以通行
if (pass(map, curpos)) {
Elemtype p;
foot(map,curpos);
p.dir = 1;
p.e = curpos;
push(L, p);//可以走就入栈
curpos = nexpos(curpos, 1);
if (curpos.x == end.x && curpos.y == end.y) {//栈中存放的就是路径点
Elemtype e;
while (!empty(L)) {//从栈里面弹出来就是路径
pop(L, e);
map[e.e.x][e.e.y] = 2;
}
for (int a = 0; a < N; a++){//优化掉不能走的地方
for (int n = 0; n < N; n++) {
if (map[a][n] == 3) {
map[a][n] = 0;
}
}
}
map[end.x][end.y] = 2;
return;
}
}
else {//当前位置不能通过
if (!empty(L)) {
Elemtype p;
pop(L, p);
while (p.dir == 4 && !empty(L)) {//四周都走过了
makeprint(map,p.e);
pop(L, p);
}
if (p.dir < 4) {//找四周可以通过的地方
p.dir++;
curpos = p.e;
curpos = nexpos(curpos, p.dir);//下一步
push(L, p);//把当前压入栈中
}
}
}
} while (!empty(L));
}
int main(){
int map[N][N];
pos start, end;
creat(map, N, N);
showmaze(map, N, N);
printf(“input the start and end postion:”);
scanf_s("(%d,%d)(%d,%d)",&start.x, &start.y, &end.x, &end.y);
maze(map,start,end);
showmaze(map, N, N);
return 0;
}