#include<iostream>
using namespace std;
#define OK 1;
//图的邻接矩阵存储表示
#define MaxInt 32767
#define MVNum 100
typedef char VerTextType;
typedef int ArcType;
typedef int Status;
typedef char TElemType;
#define MAXQSIZE 100
#define ERROR 0
typedef int QElemType;
typedef struct
{
VerTextType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum, arcnum;
}AMGraph;
int LocateVex(AMGraph G, VerTextType u)
{
int i;
for (i = 0; i < G.vexnum; ++i)
if (u == G.vexs[i])
return i;
return -1;
}
Status CreateUDN(AMGraph& G)//图的创建
{
int i, j;
int k = 0;
cin >> G.vexnum >> G.arcnum;
for (i = 0; i < G.vexnum; ++i)
cin >> G.vexs[i];
for (i = 0; i < G.vexnum; ++i)
for (j = 0; j < G.arcnum; ++j)
G.arcs[i][j] = 0;
for (k = 0; k < G.arcnum; ++k)
{
char v1, v2;
int w;
cin >> v1 >> v2 >> w;
i = LocateVex(G, v1);
j = LocateVex(G, v2);
G.arcs[i][j] = w;
G.arcs[j][i] = G.arcs[i][j];
}
return OK;
}
typedef struct//定义队列
{
QElemType* base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue& Q)//队列初始化
{
Q.base = new QElemType[MAXQSIZE];
if (!Q.base)exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
Status EnQueue(SqQueue& Q, QElemType e)//入队
{
if ((Q.rear + 1) % MAXQSIZE == Q.front)
return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue& Q, QElemType& e)//出队
{
if (Q.front == Q.rear)return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
Status isEmptyQueue(SqQueue& Q)//判空
{
if (Q.front == Q.rear)return 1;
else return 0;
}
bool visited[MVNum];
void BFS(AMGraph G, int v)//广度优先遍历
{
SqQueue Q;
QElemType u;
int w;
cout <<G.vexs[v];
visited[v] = true;
InitQueue(Q);
EnQueue(Q, v);
while (!isEmptyQueue(Q))
{
DeQueue(Q, u);
for (w = 0; w < G.vexnum; w++)
if ((G.arcs[u][w] != 0) && (!visited[w]))
{
cout <<G.vexs[ w];
visited[w] = true;
EnQueue(Q, w);
}
}
}
void BFSTraverse(AMGraph G)
{
int v;
for (v = 0; v < G.vexnum; ++v)
visited[v] = false;
for (v = 0; v < G.vexnum; ++v)
if (!visited[v])
BFS(G, v);
}
int main()
{
AMGraph G;
cout << "请输入:" << endl;
CreateUDN(G);
cout << "广度优先遍历的结果为:" << endl;
BFSTraverse(G);
return 0;
}
【C++】图的广度优先遍历操作
最新推荐文章于 2024-05-21 09:17:14 发布