【C++】图的广度优先遍历操作

#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;
}

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值