第六章算法6.7-广度优先搜索遍历连通图

代码实现
#pragma once
#include <iostream>
using namespace std;
#define MVNum 100
typedef int OtherInfo;
typedef char VerTexType;
typedef struct ArcNode
{
int adjvex;
struct ArcNode* nextarc;
OtherInfo info;
}ArcNode;
typedef struct VexNode
{
VerTexType data;
ArcNode* firstarc;
}VexNode, AdjList[MVNum];
typedef struct
{
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
int LocateVex(ALGraph G, VerTexType v)
{
for (int i = 0; i < G.vexnum; i++)
{
if (v == G.vertices[i].data)
{
return i;
}
}
}
void CreateUDG(ALGraph& G)
{
cout << "请输总顶点数:";
cin >> G.vexnum;
cout << "请输总边数:";
cin >> G.arcnum;
for (int i = 0; i < G.vexnum; i++)
{
cout << "输入顶点"<<i<<": ";
cin >> G.vertices[i].data;
G.vertices[i].firstarc = NULL;
}
VerTexType v1, v2;
ArcNode* p1;
ArcNode* p2;
ArcNode* temp1;
ArcNode* temp2;
for (int k = 0; k < G.arcnum; k++)
{
cout << "输入一条边依附的两个顶点:";
cin >> v1 >> v2;
int i = LocateVex(G, v1);
int j = LocateVex(G, v2);
p1 = new ArcNode;
p1->adjvex = j;
p1->nextarc = NULL;
temp1 = G.vertices[i].firstarc;
if (temp1 == NULL)
{
G.vertices[i].firstarc = p1;
}
else
{
while (temp1 ->nextarc != NULL)
{
temp1 = temp1->nextarc;
}
temp1->nextarc = p1;
}
p2 = new ArcNode;
p2->adjvex = i;
p2->nextarc = NULL;
temp2 = G.vertices[j].firstarc;
if (temp2 == NULL)
{
G.vertices[j].firstarc = p2;
}
else
{
while (temp2->nextarc != NULL)
{
temp2 = temp2->nextarc;
}
temp2->nextarc = p2;
}
}
}
void ShowGraph(ALGraph G)
{
for (int i = 0; i < G.vexnum; i++)
{
cout << G.vertices[i].data << " ";
ArcNode* temp = G.vertices[i].firstarc;
while (temp!= NULL)
{
cout << temp->adjvex << " ";
temp = temp->nextarc;
}
cout << endl;
}
}
#define MAXQSIZE 100
typedef struct
{
int *base;
int front;
int rear;
} SqQueue;
void initQueue(SqQueue& Q)
{
Q.base = new int[MAXQSIZE];
Q.front = Q.rear = 0;
}
void EnQueue(SqQueue& Q, int e)
{
if ((Q.rear + 1) % MAXQSIZE == Q.front)
{
cout << "队列满!" << endl;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
}
void DeQueue(SqQueue& Q, int& e)
{
if (Q.rear == Q.front)
{
cout << "队空!" << endl;
}
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
}
bool QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
{
return true;
}
return false;
}
bool visited[MVNum];
void BFS(ALGraph G, int v)
{
cout << G.vertices[v].data;
visited[v] = true;
SqQueue Q;
initQueue(Q);
EnQueue(Q, v);
int u;
ArcNode* p;
while (!QueueEmpty(Q))
{
p = G.vertices[Q.base[Q.front]].firstarc;
DeQueue(Q, u);
while (p != NULL)
{
int w = p->adjvex;
if (!visited[w])
{
cout << G.vertices[w].data;
visited[w] = true;
EnQueue(Q, w);
}
p = p->nextarc;
}
}
}
int main()
{
ALGraph G;
CreateUDG(G);
ShowGraph(G);
for (int i = 0; i < G.vexnum; i++)
{
visited[i] = false;
}
cout << "从哪个顶点开始DFS?" << endl;
int v;
cin >> v;
BFS(G, v);
cout << endl;
system("pause");
return 0;
}
运行结果