从第一个状态开始,沿着剩余的符合条件的路径继续搜索,直到找到解/满足结束条件为止
比如遍历迷宫,从起点到终点,每次可以上下左右移动,移动了再以此为据点再上下左右移动,就这样一步步移动到终点,但是也要注意重复绕路的情况,这样是会造成死循环的,因此可以用一个数组记录是否走过这个坐标
第一个测试用例不用全局声明
lambda包含lambda(赋值给std::function):
#include"boost/function.hpp"
void test02() {
#define max_line 50
#define max_col 50
int line = 5, col = 4, minstep = max_line * max_col;
int map[max_line][max_col], visited[max_line][max_col];//防止回头重复
int nextAxis[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };//上下左右移动
int s_x = 0, s_y = 0, e_x = 3, e_y = 2;//起点终点
for (int i = 0; i < line; i++)
for (int j = 0; j < col; j++) {
map[i][j] = 0;
visited[i][j] = 0;
}//初始化迷宫
map[0][2] = map[2][2] = map[3][1] = map[4][3] = 1;//设置障碍点
visited[s_x][s_y] = 1;//起点
auto func = [&](int x, int y, int step)->void {
std::function<void(int, int, int)> _func;
_func = [&](int x, int y, int step) {
if (x == e_x && y == e_y) {
minstep = minstep < step ? minstep : step;
return;
}
int n_x, n_y;
for (int i = 0; i < 4; i++) {
n_x = x + nextAxis[i][0];
n_y = y + nextAxis[i][1];
if (n_x<0 || n_x>col - 1 || n_y<0 || n_y>line - 1)continue;//越界跳过
if (map[n_x][n_y] == 0 && visited[n_x][n_y] == 0) {
visited[n_x][n_y] = 1;
_func(n_x, n_y, step + 1);
visited[n_x][n_y] = 0;
}
}
};
_func(x, y, step);
};
func(s_x, s_y, 0);
cout << minstep << endl;
}
直接全局定义函数:
void dfs(int x, int y, int step) {
if (x == e_x && y == e_y) {
minstep = minstep < step ? minstep : step;
return;
}
int n_x, n_y;
for (int i = 0; i < 4; i++) {
n_x = x + nextAxis[i][0];
n_y = y + nextAxis[i][1];
if (n_x<0 || n_x>col-1 || n_y<0 || n_y>line-1)continue;//越界跳过
if (map[n_x][n_y] == 0 && visited[n_x][n_y] == 0) {
visited[n_x][n_y] = 1;
dfs(n_x, n_y, step + 1);
visited[n_x][n_y] = 0;
}
}
}
lambda包含lambda:
void test02() {
#define max_line 50
#define max_col 50
int line = 5, col = 4, minstep = max_line * max_col;
int map[max_line][max_col], visited[max_line][max_col];
int nextAxis[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };//上下左右移动
int s_x = 0, s_y = 0, e_x = 3, e_y = 2;//起点终点
for (int i = 0; i < line; i++)
for (int j = 0; j < col; j++) {
map[i][j] = 0;
visited[i][j] = 0;
}//初始化迷宫
map[0][2] = map[2][2] = map[3][1] = map[4][3] = 1;//设置障碍点
visited[s_x][s_y] = 1;//起点
const auto& func = [&](int x, int y, int step)->void {
const auto& _func = [&](auto&& self, int x, int y, int step)->void {
if (x == e_x && y == e_y) {
minstep = minstep < step ? minstep : step;
return;
}
int n_x, n_y;
for (int i = 0; i < 4; i++) {
n_x = x + nextAxis[i][0];
n_y = y + nextAxis[i][1];
if (n_x<0 || n_x>col - 1 || n_y<0 || n_y>line - 1)continue;//越界跳过
if (map[n_x][n_y] == 0 && visited[n_x][n_y] == 0) {
visited[n_x][n_y] = 1;
self(self, n_x, n_y, step + 1);
visited[n_x][n_y] = 0;
}
}
};
_func(_func, x, y, step);
};
func(s_x, s_y, 0);
cout << minstep << endl;
}