广度优先搜素
一、用到的知识点
1、队列
#include <queue>
queue<int> gQueue
gQueue.push(0)
gQueue.front():得到最先插入的数据
gQueue.pop()
二、使用到的函数
1、BFS()
#include "pch.h"
#include <iostream>
#include <stack>
#include <queue>
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);
}
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;
}
}
void BFS() {
queue<int> gQueue;
vertexList[0]->wasVisited = true;
showVertex(0);
gQueue.push(0);
int v1, v2;
while (gQueue.size() > 0) {
v1 = gQueue.front();
gQueue.pop();
v2 = getNextUnvisitedVertex(v1);
while (v2 != -1) {
gQueue.push(v2);
showVertex(v2);
vertexList[v2]->wasVisited = true;
v2 = getNextUnvisitedVertex(v1);
}
}
cout << endl;
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;
}