## 第六章 回溯法

::: hljs-center

●前言

●一、回溯法是什么？

1.简要介绍

●二、回溯法经典案例——兔子走迷宫游戏

1.具体情况

2.代码展示（C++）

3.结果展示

●总结

## 二、回溯法经典案例——兔子走迷宫游戏

### 2.代码展示（C++）

``````#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;
{
newnode = new node;
if (!newnode)
{
return NULL;
}
newnode->x = x;
newnode->y = y;
newnode->next = stack;
stack = newnode;
return stack;
}
{
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()
{
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();  //输出最终老鼠走过路径的迷宫矩阵
}
``````

（图一） （图二）

## 总结

<您的三连和关注是我最大的动力> 🚀 文章作者：Keanu Zhang 分类专栏：算法之美（C++系列文章）