图的深度广度 优先遍历

//邻接矩阵数据类型定义
#define MAXV 最大顶点个数
typedef char ElemType;
typedef struct
{
	int no;
	ElemType info;
}VertexType;
typedef struct
{
	int edges[MAXV][MAXV];
	int n,e;
	VertexType vexs[MAXV];
}MGraph;

//邻接表的存储表示
typedef char ElemType;
typedef int InfoType;
typedef struct ANode
{
	int adjvex;
	struct ANode *nextarc;
	InfoType info;
}ArcNode;
typedef struct Vnode
{
	ElemType data;
	ArcNode *firstarc;
}VNode;
typedef struct
{
	VNode adjlist[MAXV];
	int n,e;
}AGraph;

//连通图,邻接表,深度优先遍历
int visited[MAXV];
void DFS(AGraph *G,int v)
{
	ArcNode *p;
	visited[v]=1;
	printf("%d ",v);
	p=G->adjlist[v].firstarc;
	while(p!=NULL)
	{
		if(visited[p->adjvex]==0)
			DFS(G,p->adjvex);
		p=p->nextarc;
	}
}


//连通图,邻接表,广度优先遍历
void BFS(AGraph *G,int v)
{
	ArcNode *p;
	int queue[MAXV],front=0,rear=0;
	int visited[MAXV];
	int w,i;
	for(i=0;i<G->n;i++)
		visited[i]=0;
	printf("%d ",v);    //先访问,再入队
	visited[v]=1;
	rear=(rear+1)%MAXV;
	queue[rear]=v;
	while(front!=rear)
	{
		front=(front+1)%MAXV;
		w=queue[front];
		p=G->adjlist[w].firstarc;
		while(p!=NULL)
		{
			if(visited[p->adjvex]==0)
			{
				printf("%d ",p->adjvex);
				visited[p->adjvex]=1;
				rear=(rear+1)%MAXV;
				queue[rear]=p->adjvex;
			}
			p=p->nextarc;
		}
	}
	printf("\n");
}


//非连通图,邻接表,深度优先遍历
DFS1(AGraph *G)
{
	int i;
	for(i=0;i<G->n;i++)
	{
		if(visited[i]==0)
			DFS(G,i);
	}
}

//非连通图,邻接表,广度优先遍历
BFS1(AGraph *G)
{
	int i;
	for(i=0;i<G->n;i++)
	{
		if(visited[i]==0)
			BFS(G,i);
	}
}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/ndzjx/article/details/42455191
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞