# 深度优先搜索DFS C++实现

//DFS，使用 邻接矩阵+栈 实现
#include <iostream>
#include <stack>

using namespace std;

#define MAX_VERTS 20

class Vertex
{
public:
Vertex(char lab)
{
Label = lab;
wasVisited = false;
}
public:
bool wasVisited;
char Label;
};

class Graph
{
public:
Graph();
~Graph();
void printMatrix();
void showVertex(int v);
void DFS();
private:
Vertex* vertexList[MAX_VERTS];
int nVerts;

};

Graph::Graph()
{
nVerts = 0;
for (int i = 0; i < MAX_VERTS; i++)
{
for (int j = 0; j < MAX_VERTS; j++)
{
}
}
}

Graph::~Graph()
{
//delete[] vertexList;
}
//添加顶点
{
vertexList[nVerts++] = new Vertex(lab);
}
//添加边
{
}

void Graph::printMatrix()
{
for (int i = 0; i < nVerts; i++)
{
for (int j = 0; j < nVerts; j++)
{
cout << adjMat[i][j] << " ";
}
cout << endl;
}
}
//显示顶点标签
void Graph::showVertex(int v)
{
cout << vertexList[v]->Label << " ";
}

//获得未访问过的下一个顶点
{
for (int j = 0; j < nVerts; j++)
{
//邻接的并且没被访问过
if ((adjMat[v][j] == 1) && (vertexList[j]->wasVisited == false))
return j;
}

return -1;
}
//深度优先搜索
void Graph::DFS()
{
stack<int> gStack;
vertexList[0]->wasVisited = true;
showVertex(0);
//要把访问过的顶点压入栈中
gStack.push(0);
int v;
while (gStack.size() > 0)
{
//访问当前顶点的下一个
//如果没找到就利用栈向回找
if (v == -1)
gStack.pop();
else
{
vertexList[v]->wasVisited = true;
showVertex(v);
gStack.push(v);
}
}
cout << endl;
//为了下一次搜索再把wasVisited变成false
for (int j = 0; j < nVerts; j++)
vertexList[j]->wasVisited = false;
}

int main()
{
Graph g;

g.printMatrix();

g.DFS();

system("pause");
return 0;
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客