用矩阵(二维数组)表示迷宫,其中1表示墙,0表示通路。老鼠在左上角,要走到迷宫右下角。
很简单的一个问题,主要是利用栈来记录走的每一步。还有就是在原始迷宫周围加上一圈“墙”,,避免边缘路径需要特殊处理(直接取值可能出现数组越界)。直接贴代码
//老鼠走迷宫问题
#include"stack.h"
#define X 10
class Point {
public:
int x;
int y;
char dir;
Point(){}
Point(int x1, int y1, char dir1){
x = x1;
y = y1;
}
};
int main() {
int maze[X][X] = { { 0, 1, 1, 1, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 },
{ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0, 1, 0, 1, 1, 0 },
{ 0, 1, 0, 1, 0, 1, 0, 1, 0, 0 },
{ 0, 1, 1, 1, 0, 1, 0, 1, 0, 1 },
{ 0, 1, 0, 0, 0, 1, 0, 1, 0, 1 },
{ 0, 1, 0, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0 },
};
Stack s(50);
//在原始迷宫周围加上墙
int maze2[X + 2][X + 2];
for (int ii = 0; ii < X + 2; ii++){
for (int j = 0; j < X + 2; j++){
if (ii == 0 || ii == X + 1) {
maze2[ii][j] = 1;
}
else if (j == 0 || j == X + 1){
maze2[ii][j] = 1;
}
else{
maze2[ii][j] = maze[ii - 1][j - 1];
}
}
}
//从0,1开始
int i = 1;
int j = 1;
while (!(i == X && j == X)) {
//向右
if (maze2[i][j - 1] == 0) {
Point p(i, j, 'r');
s.add(p);
maze2[i][j] = 2; //标记走过的点
j = j - 1;
}
else
//向下
if (maze2[i + 1][j] == 0){
Point p(i, j, 'd');
s.add(p);
maze2[i][j] = 2; //标记走过的点
i = i + 1;
}
//向左
else if (maze2[i][j + 1] == 0){
Point p(i, j, 'l');
s.add(p);
maze2[i][j] = 2; //标记走过的点
j = j + 1;
}
//向上
else if (maze2[i - 1][j] == 0){
Point p(i, j, 'u');
s.add(p);
maze2[i][j] = 2; //标记走过的点
i = i - 1;
}
//回溯
else if (!s.isEmpty()){
Point p;
s.Delete(p);
maze2[i][j] = 2;
i = p.x;
j = p.y;
}
else {
cout << "oohh!wrong maze" << endl;
}
}
Point p;
while (!s.isEmpty()){
s.Delete(p);
cout << '(' << p.x << "," << p.y << ")<-";
}
}
刚开始写的时候没有将走过的格子置为2,所以还设置了变量来记录方向,后来开到别人的代码发现标记走过的格子更简单。