图的邻接表BFS(参考C博客—研究毛)

本文介绍了如何使用C++实现图的邻接表数据结构,并利用该结构进行广度优先搜索(BFS)。通过创建ALGraph结构体,初始化队列,设置标记数组来跟踪已访问节点,以及Visit函数输出访问节点,实现了图的BFS遍历。
摘要由CSDN通过智能技术生成
#include<iostream>
using namespace std;
#define QSIZE 20
#define MAXVEX 30
typedef char VType;
typedef int EType;
typedef struct ENode
{
	int Avex;
	struct ENode *pNext;
}ENode, *pENode;
typedef struct VNode
{
	VType data;
	ENode *pFirst;
}VNode, VNodeL[MAXVEX];
typedef struct
{
	VNodeL VLnode;
	int Vnums;
	int Enums;
}ALGraph;
typedef struct Queue
{
	int *pBase;
	int Front;
	int Rear;
}Queue;
void InitQueue(Queue &Q)
{
	Q.pBase = new int[QSIZE];
	Q.Front = 0;
	Q.Rear = 0;
}
bool QueueFull(Queue &Q)
{
	if ((Q.Rear + 1) % QSIZE == Q.Front)
		return true;
	else
		return false;
}
bool QueueEmpty(Queue &Q)
{
	if (Q.Front == Q.Rear)
		return true;
	else
		return false;
}
bool EnQueue(Queue &Q, int pos)
{
	if (QueueFull(Q))
		return false;
	Q.pBase[Q.Rear] = pos;
	Q.Rear = (Q.Rear + 1) % QSIZE;
}
bool DeQueue(Queue &Q,int &pos)
{
	if (QueueEmpty(Q))
		return false;
	pos = Q.pBase[Q.Front];
	Q.Front = (Q.Front + 1) % QSIZE;
}
void CreateALGraph(ALGraph &G)
{
	int i, j, k;
	ENode *pE;
	cin >> G.Vnums >> G.Enums;
	for (i = 0; i < G.Vnums; ++i)
	{
		cin >> G.VLnode[i].data;
		G.VLnode[i].pFirst = NULL;
	}
	for (k = 0; k < G.Enums; ++k)
	{
		cin >> i >> j;
		pE = new ENode;
		pE->Avex = i;
		pE->pNext = G.VLnode[j].pFirst;
		G.VLnode[j].pFirst = pE;
		pE = new ENode;
		pE->Avex = j;
		pE->pNext = G.VLnode[i].pFirst;
		G.VLnode[i].pFirst = pE;
	}
}
bool VTag[MAXVEX];
void Visit(VType v)
{
	cout << v << " ";
}
void BFSPrint(ALGraph G)
{
	int i, j;	
	pENode pE;
	Queue Q;
	InitQueue(Q);
	for (i = 0; i < G.Vnums; ++i)
		VTag[i] = false;
	for (i = 0; i < G.Vnums; ++i)
	{
		if (!VTag[i])
		{
			VTag[i] = true;
			Visit(G.VLnode[i].data);
			EnQueue(Q,i);
			while (!QueueEmpty(Q))
			{
				DeQueue(Q,i);
				pE = G.VLnode[i].pFirst;
				while (pE)//是否有相邻边表结点
				{
					if (!VTag[pE->Avex])//是否被访问过
					{
						VTag[pE->Avex] = true;
						Visit(G.VLnode[pE->Avex].data);
						EnQueue(Q, pE->Avex);
					}
					pE = pE->pNext;
				}
			}			
		}
	}

}
int main(void)
{
	ALGraph G;
	CreateALGraph(G);
	BFSPrint(G);
	return(0);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值