深度广度优先算法、A*算法
深度优先算法(DFS)
深度优先搜索属于图算法的一种,是一个针对图和树的遍历算法,英文缩写为DFS即Depth First Search。深度优先搜索是图论中的经典算法,利用深度优先搜索算法可以产生目标图的相应拓扑排序表,利用拓扑排序表可以方便的解决很多相关的图论问题,如最大路径问题等等。一般用堆数据结构来辅助实现DFS算法。其过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次。
实现步骤
在这里我用一个数组来进行实现,1作为起点,44作为终点
指定上下左右的顺序,按照顺序的优先级来遍历,优先级高的能走则优先走
1.从起点开始,由于上超出数组不能走,则开始向下走,同时将起点标记为走过的状态;由于上下的优先级比较高,所以一直走到55;
2.当到达55的时候,上下左都不能走,则向右走一步,发现不是终点,同时上可以走,则先走上方向
3.按照这种顺序一直走,直到走到33的位置
4.这个时候发现在33的位置每个方向都走不通,那么我们就来后退一步,然后按照之前的顺序继续遍历
5.当我们走到终点,就输出路径
实现代码
Map.h
#pragma once
#include <iostream>
using namespace std;
enum
{
START,
END,
WALL,
OLD,
};
class Map
{
public:
int m_nMap[7][9];
int m_nMap2[9][11];
Map();
~Map();
};
Map.cpp
#include "stdafx.h"
#include "Map.h"
Map::Map()
{
int n = 1;
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 9; j++)
{
m_nMap[i][j] = n;
n++;
}
}
int Map[9][11] =
{
{
WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL },
{
WALL, START, 0, 0, 0, 0, 0, WALL, 0, 0, WALL },
{
WALL, 0, 0, WALL, WALL, 0, 0, WALL, 0, 0, WALL },
{
WALL, 0, 0, WALL, 0, 0, WALL, WALL, 0, 0, WALL },
{
WALL, 0, 0, 0, WALL, 0, 0, WALL, 0, 0, WALL },
{
WALL, 0, 0, 0, WALL, 0, 0, 0, END, 0, WALL },
{
WALL, 0, 0, 0, 0, 0, 0, 0, 0, 0, WALL },
{
WALL, 0, 0, 0, WALL, 0, 0, 0, 0, 0, WALL },
{
WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL },
};
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 11; j++)
{
m_nMap2[i][j] = Map[i][j];
}
}
}
Map::~Map()
{
}
Breath.h
#pragma once
#include <vector>
using namespace std;
#include "Map.h"
struct Pos1
{
int x;
int y;
int sign;
};
class Breadth
{
vector<Pos1> PosVector;
Map map;
public:
bool BFS(int x, int y,int sign);
void GetRoad();
Breadth();
~Breadth();
};
Breath.cpp
#include "stdafx.h"
#include "Breadth.h"
Breadth::Breadth()
{
}
bool Breadth::BFS(int x, int y, int sign)
{
Pos1 pos = {
x, y, sign };
//1.将起点添加到路径中
PosVector.push_back(pos);
int i = 0;
while (i < PosVector.size())
{
int z = PosVector.size() - 1;
int Posx = PosVector[i].x + 1, Posy = PosVector[i].y + 1;
if (map.m_nMap2[Posx][Posy] == END)
{
return 1;
}
else
{
int m = PosVector[i].x;
int n = PosVector[i].y;
sign++;
if (map.m_nMap2[Posx - 1][Posy] == 0 || map.m_nMap2[Posx - 1][Posy] == END)
{
map.m_nMap2[Posx][Posy] = OLD;
if (map.m_nMap2[Posx - 1][Posy] == END)
{
Pos1 end = {
m - 1, n, sign };
PosVector.push_back(end);
return 1;
}
else
map.m_nMap2[Posx - 1][Posy] = OLD;
Pos1 temp = {
m