深度优先搜索(DFS)
一、使用到的知识点
1、使用堆栈(最后一个顶点最先可以得到)
stack<int> gStack:创建一个堆类
gStack.push(0):压入一个int类型数据
gStack.size() > 0:返回堆的空间
gStack.pop():删除一个堆中的数据
gStack.top():得到堆中最后压入的数据
2、邻接矩阵
矩阵中对于相邻的两点置为1,不相邻的两点为0
3、指针数组
用于存放一系列指向顶点的指针
二、重要函数
1、getNextUnvisitedVertex(int v)
给一个点得到下一个没有访问过的点,若没有则返回-1
2、showVertex(int t)
显示出对应的顶点
3、DFS()
#include "pch.h"
#include <iostream>
#include <stack>
using namespace std;
#define MAX_VERTS 20
class Vertex {
public:
Vertex(char lab) {
label = lab;
wasVisited = false;
}
char label;
bool wasVisited;
};
class Graph {
Vertex* vertexList[MAX_VERTS];
int nVerts;
int adjMat[MAX_VERTS][MAX_VERTS];
int getNextUnvisitedVertex(int v) {
for (int i = 0; i < nVerts; i++) {
if (adjMat[v][i] == 1 && vertexList[i]->wasVisited == false) {
return i;
}
}
return -1;
}
public:
Graph() {
nVerts = 0;
for (int i = 0; i < MAX_VERTS; i++) {
for (int j = 0; j < MAX_VERTS; j++) {
adjMat[i][j] = 0;
}
}
}
~Graph() {
for (int i = 0; i < nVerts; i++) {
delete vertexList[i];
}
}
void addVertex(char lab) {
vertexList[nVerts++] = new Vertex(lab);
nVerts++;
}
void addEdge(int start, int end) {
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
void printMat() {
for (int i = 0; i < nVerts; i++) {
for (int j = 0; j < nVerts; j++) {
cout << adjMat[i][j] << " " ;
}
cout << endl;
}
}
void showVertex(int t) {
cout << vertexList[t]->label << ' ';
}
void DFS() {
stack<int> gStack;
vertexList[0]->wasVisited = true;
showVertex(0);
gStack.push(0);
int v;
while (gStack.size() > 0) {
v = getNextUnvisitedVertex(gStack.top());
if (v == -1) {
gStack.pop();
}
else {
vertexList[v]->wasVisited = true;
showVertex(v);
gStack.push(v);
}
}
for (int i = 0; i < nVerts; i++) {
vertexList[i]->wasVisited = false;
}
}
};
int main()
{
Graph g;
g.addVertex('A');
g.addVertex('B');
g.addVertex('C');
g.addVertex('D');
g.addVertex('E');
g.addEdge(0, 1);
g.addEdge(0, 3);
g.addEdge(1, 0);
g.addEdge(1, 4);
g.addEdge(2, 4);
g.addEdge(3, 0);
g.addEdge(3, 4);
g.addEdge(4, 1);
g.addEdge(4, 2);
g.addEdge(4, 3);
g.printMat();
system("pause");
return 0;
}