#include<iostream>
using namespace std;
#define north maze[x-1][y] //北
#define south maze[x+1][y] //南
#define west maze[x][y-1] //西
#define east maze[x][y+1] //东
int maze[12][12] = { {0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,0,0,0,0,0,0,0,0},
{0,0,0,1,0,0,1,1,1,1,0,0},
{0,0,0,1,0,0,1,0,0,1,0,0},
{0,0,0,1,1,1,1,0,0,1,0,0},
{0,0,0,1,0,0,1,0,0,1,0,0},
{0,0,0,1,0,0,1,0,0,1,0,0},
{0,0,0,1,0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,1,0,0,1,0,0},
{0,0,1,1,1,1,1,1,0,1,1,0},
{0,0,1,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0} }; //二维数组迷宫图,0表示墙,1表示通路
const int exitx = 9, exity = 10; //出口端在数组迷宫中的位置,9行10列
//链表的定义及其记录使用
struct list {
int x, y;
struct list* next;
};
typedef struct list node;
typedef node* link;
link push(link stack,int x,int y)
{
link newnode;
newnode = new node;
if (!newnode)
{
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= top->x;
*y = top->y;
delete top;
return stack;
}
else
{
*x = -1;
}
return stack;
}
//
int checkexit(int x,int y) //检查是否到达终点
{
if (x == exitx && y == exity)
return 1;
else
return 0;
}
class maze_data {
public:
int x;
int y;
void walk_judgement()
{
link path = NULL; //初始化路径
while (x <= exitx && y <= exity) //while循环中进行东南西北四个方位移动的判断
{
maze[x][y] = 2;
if (north == 1) //上一格可走
{
x--; //往上走
path = push(path, x, y); //加入方格编号到对堆栈
}
else if (south == 1) //下一个可走
{
x++; //往下走
path = push(path, x, y); //加入方格编号到对堆栈
}
else if (west == 1) //左一格可走
{
y--; //往左走
path = push(path, x, y); //加入方格编号到对堆栈
}
else if (east == 1) //右一格可走
{
y++; //往右走
path = push(path, x, y); //加入方格编号到对堆栈
}
else if (checkexit(x, y) == 1) //如果判断到已经到达终点,从而跳出循环
break;
else //记录走过的位置
{
maze[x][y] = 2;
path = pop(path, &x, &y);
}
}
}
};
void text1()
{
cout << "-----------------------" << endl;
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++)
{
cout << maze[i][j] << " ";
}
cout << endl;
}
cout << "-----------------------" << endl;
}
void text2()
{
maze_data md;
md.x = 1;
md.y = 1;
md.walk_judgement();
}
int main()
{
text1(); //输出初始的迷宫矩阵
text2();
text1(); //输出最终老鼠走过路径的迷宫矩阵
}