#include <iostream>
#include <stack> // 堆栈,
#include <queue> // 队列,
#define MAX_VERTS 20
using namespace std;
class Vertex
{
public:
Vertex(char lab)
{
Label = lab;
wasVisited = false;
}
public:
bool wasVisited;
char Label;
};
class Graph // 这是一个图,
{
public:
Graph();
~Graph();
void addVertex(char lab); // 增加一个定点,就是一个字符,
void addEdge(int start, int end); // 增加一条边,
void printMatrix(); // 将矩阵显示出来,
void showVertex(int v); // 显示顶点的字符函数,
void DFS();
void BFS();
private:
Vertex* vertexList[MAX_VERTS];
int nVerts; // 这个保存定点的个数,
int adjMat[MAX_VERTS][MAX_VERTS]; // 定义一个矩阵,20*20的,
int getAdjUnvisitedVertex(int v); // 显示下一个临接的顶点,
};
void Graph::DFS()
{
stack<int> gStack; // 这个堆栈保存int类型的,
vertexList[0]->wasVisited = true;
showVertex(0);
gStack.push(0);
int v;
while(gStack.size() > 0)
{
v = getAdjUnvisitedVertex(gStack.top());
if (v == -1) // 如果下一个不存在将返回,
gStack.pop();
else
{
vertexList[v]->wasVisited = true;
showVertex(v);
gStack.push(v);
}
}
cout << endl;
for(int j = 0; j < nVerts; j++)
vertexList[j]->wasVisited = false; // 这是将访问过的变成false,没有访问过,
}
void Graph::BFS()
{
queue<int> gQueue; // 队列保存队列中的下标,
vertexList[0]->wasVisited = true;
showVertex(0);
gQueue.push(0);
int vert1,vert2;
while(gQueue.size() > 0)
{
vert1 = gQueue.front();
gQueue.pop();
vert2 = getAdjUnvisitedVertex(vert1);
while(vert2 != -1)
{
vertexList[vert2]->wasVisited = true; // 判断显示过了,
showVertex(vert2); // 将其显示出来,
gQueue.push(vert2); // 将其放入到队列中,
vert2 = getAdjUnvisitedVertex(vert1);
}
}
cout << endl;
for(int j = 0; j < nVerts; j++)
vertexList[j]->wasVisited = false;
}
int Graph::getAdjUnvisitedVertex(int v)
{
for(int j = 0; j < nVerts; j++)
if((adjMat[v][j] == 1) && (vertexList[j]->wasVisited == false))
return j;
return -1;
}
void Graph::showVertex(int v) // v 是顶点的下标,
{
cout << vertexList[v]->Label << " ";
}
Graph::Graph() // 这个是构造函数,
{
nVerts = 0;
for(int i = 0; i < MAX_VERTS; ++i)
for(int j = 0; j < MAX_VERTS; ++j)
adjMat[i][j] = 0;
}
void Graph::addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
void Graph::addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
void Graph::printMatrix()
{
for(int i = 0; i < nVerts; i++)
{
for(int j = 0; j < nVerts; j++)
cout << adjMat[i][j] << " ";
cout << endl;
}
}
Graph::~Graph()
{
for(int i = 0; i < nVerts; i++)
delete vertexList[i];
}
int main()
{
Graph g;
g.addVertex('A'); // 0 是下标为0,
g.addVertex('B'); // 1 是下标为1,
g.addVertex('C'); // 2 是下标为2,
g.addVertex('D'); // 3 是下标为3,
g.addVertex('E'); // 4 是下标为4,
g.addEdge(0,1); // A-B 用下标表示A与B相连,
g.addEdge(0,3); // A-D
g.addEdge(1,0); // B-A
g.addEdge(1,4); // B-E
g.addEdge(2,4); // C-E
g.addEdge(3,0); // D-A
g.addEdge(3,4); // D-E
g.addEdge(4,1); // E-B
g.addEdge(4,2); // E-C
g.addEdge(4,3); // E-D
g.printMatrix();
cout << "深度优先搜索的结果: ";
g.DFS(); // 输出是A B E C D
cout << "广度优先搜索的结果: ";
g.BFS(); // 输出是 A B D E C
return 0;
}
广度 / 深度优先搜索
最新推荐文章于 2024-03-09 14:07:59 发布