什么是深度优先算法?
其实就类似我们自己走迷宫,我们会找一条路一直走,走到死胡同里了就回退到上一个分叉路口,继续选择一条之前没走过的路。如此重复,一定能找到终点。
理解起来很简单,那怎么用代码去实现呢?
其实就是把这句话用代码去实现 “ 我们会找一条路一直走,走到死胡同里了就回退到上一个分叉路口,继续选择一条之前没走过的路。如此重复 ”
1、
关键词回退,怎么回退,可以用栈结构存储你所走过的坐标点,如果走到死胡同,就往后退一格(即出栈),再走,还是死胡同,再退,再走······
2、
什么是死胡同:就是周围都是墙或者是已经走过的路
3、
怎么判断路走没走过:现在我们用数组(1为墙,0为路)保存迷宫,那么我们可以再定义一个相同大小的【走过】数组,先全赋值为0,如果走过迷宫处某点,就把对应位置的【走过】数组赋1
4、
怎么选择方向:其实方向可以随意选择,在这里我们用先一直往上走,走不了了再换成左,走不了了再换成下,走不了了再换成右
用数组自定义一个迷宫
int Map[10][10] = {//自定义迷宫
1,1,1,1,1,1,1,1,1,1,
1,0,0,0,0,1,0,0,0,1,
1,0,0,1,0,1,0,1,0,1,
1,0,0,1,0,1,0,0,0,1,
1,1,1,1,0,1,0,1,0,1,
1,0,0,0,0,1,0,1,0,1,
1,0,1,1,0,0,0,1,0,1,
1,0,0,1,0,1,0,1,0,1,
1,0,0,1,0,0,0,1,0,1,
1,1,1,1,1,1,1,1,1,1,
};
简单的源代码
#include<iostream>
#include<string>
#include<stack>
using namespace std;
struct MyPoint {//表示迷宫上的点坐标
int row;
int col;
};
int main()
{
int Map[10][10] = {//自定义迷宫
1,1,1,1,1,1,1,1,1,1,
1,0,0,0,0,1,0,0,0,1,
1,0,0,1,0,1,0,1,0,1,
1,0,0,1,0,1,0,0,0,1,
1,1,1,1,0,1,0,1,0,1,
1,0,0,0,0,1,0,1,0,1,
1,0,1,1,0,0,0,1,0,1,
1,0,0,1,0,1,0,1,0,1,
1,0,0,1,0,0,0,1,0,1,
1,1,1,1,1,1,1,1,1,1,
};
int isFind[10][10] = {//存储地图是否走过的信息
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
};
stack<MyPoint> ms;
MyPoint beginPoint = { 2,2 };//自定义起点
MyPoint endPoint = { 8,8 };//自定义终点
ms.push(beginPoint);
MyPoint currentPoint = beginPoint;//当前走到的位置
isFind[currentPoint.row][currentPoint.col] = 1;
while (1)//while循环一直走下去,一直走到终点
{
//上
if (Map[currentPoint.row - 1][currentPoint.col] == 0 &&
isFind[currentPoint.row - 1][currentPoint.col] == 0)//可以向上走的条件
{
isFind[currentPoint.row - 1][currentPoint.col] = 1;
currentPoint.row = currentPoint.row - 1;
ms.push(currentPoint);
}
//左
else if (Map[currentPoint.row][currentPoint.col-1] == 0 &&
isFind[currentPoint.row][currentPoint.col-1] == 0)//可以向左走的条件
{
isFind[currentPoint.row][currentPoint.col - 1] = 1;
currentPoint.col = currentPoint.col - 1;
ms.push(currentPoint);
}
//下
else if (Map[currentPoint.row + 1][currentPoint.col] == 0 &&
isFind[currentPoint.row + 1][currentPoint.col] == 0)//可以向下走的条件
{
isFind[currentPoint.row + 1][currentPoint.col] = 1;
currentPoint.row = currentPoint.row + 1;
ms.push(currentPoint);
}
//右
else if (Map[currentPoint.row][currentPoint.col+1] == 0 &&
isFind[currentPoint.row][currentPoint.col+1] == 0)//可以向右走的条件
{
isFind[currentPoint.row][currentPoint.col + 1] = 1;
currentPoint.col = currentPoint.col + 1;
ms.push(currentPoint);
}
else//死胡同,即上下左右都无法走
{
ms.pop();
currentPoint = ms.top();
}
if (currentPoint.row == endPoint.row && currentPoint.col == endPoint.col)
{
cout << "找到终点!路径回退:" << endl;
break;
}
if (ms.empty())
{
cout << "找不到路!" << endl;
break;
}
}
while (!ms.empty())//打印路径
{
MyPoint temp = ms.top();
cout << "row = " << temp.row << " col = " << temp.col << endl;
ms.pop();
}
return 0;
}
结果
其实基于这个原理我们还可以自己去生成迷宫。