有向图的遍历(深度遍历和广度遍历)

本文详细介绍了有向图的深度优先搜索(DFS)和广度优先搜索(BFS)两种遍历算法,包括它们的实现原理、步骤及优缺点。通过实例解析,帮助读者理解如何在实际问题中应用这两种遍历方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typedef struct  _BinaryTreeNode
{
	char data;
	//int ltag , rtag;
	struct _BinaryTreeNode *lchild;
	struct _BinaryTreeNode *rchild; 

}BTNode;

 

/创建邻接矩阵 假定这里是有向图
void  createMGraph(AGraph *a)
{
//	int i;
//	int  start;
//	int end;
	
	cout<<"请输入顶点的数目和边的数目"<<endl;
	cin>>a->n>>a->e;
	cout<<"请输入顶点的值"<<endl;
	for (int i =0;i<a->n;i++ )
	{
		cin>>a->adjlist[i].data;
		a->adjlist[i].firstarc =NULL;
	}
//创建邻接矩阵
	cout<<"请输入边:起始顶点start和终止顶点 end"<<endl;
	for (int i =0;i< a->e; i++)
	{
		int start,end;
		cin>>start>>end;
		ArcNode *e;//弧
		e= new ArcNode ;
		e->adjvex =end;
		e->nextarc = a->adjlist[start].firstarc;
		a->adjlist[start].firstarc = e;
	}
}
void BFSTraverse(AGraph *a,int v)
{
	//存的是顶点
	queue<int> q;
	if (visit[v]==1)
	{
		return;
	}
	visit[v] = 1;
	ArcNode *p ;
	cout << a->adjlist[v].data<<endl;
	while(!q.empty())
	{
		p = a->adjlist[q.front()].firstarc;
		q.pop();
		while(p!=NULL)
		{
			if (visit[p->adjvex]==0)
			{
				visit[p->adjvex] = 1;
				cout<< a->adjlist[p->adjvex].data<<endl;
				q.push(p-
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值