图的广度优先遍历和深度优先遍历(基于链式前向星)

#include<iostream>
#include<cstring> 
#include<queue>
using namespace std;

const int maxn = 100001;
int head[maxn];
bool vis[maxn];
bool bvis[maxn];

queue<int> que;

struct EdgeNode
{
	int to;
	int w;
	int next;
};

EdgeNode Edges[maxn * 3];

int k;

void init()
{
	int i;
	memset(head,-1,sizeof(head));
	memset(vis,false,sizeof(vis));
	memset(bvis,false,sizeof(vis));
	k = 0;	
}

void add(int i,int j,int w)
{
	Edges[k].w = w;
	Edges[k].to = j;
	Edges[k].next = head[i];
	head[i] = k++;
}

void traver(int m)
{
	int i,p;
	for(p=1;p<=m;p++)
	for(i=head[p];i!=-1;i=Edges[i].next)
	{
		printf("%d %d %d\n",p,Edges[i].to,Edges[i].w);
	}
}

void dfs(int x)
{
	int i;
	vis[x] = true;
	printf("%d\n",x);
	for(i=head[x];i!=-1;i=Edges[i].next)
	{
		if(!vis[Edges[i].to])
		{
			dfs(Edges[i].to);
		}
		/*else
		{
			printf("pos:%d\n",Edges[i].to);
		}*/
	}
}

void bfs(int x)
{
	que.push(x);
	bvis[x] = true;
	int i,k;
	while(!que.empty())
	{
		int x = que.front();
		que.pop();
		printf("%d\n",x);
		for(k=head[x];k!=-1;k=Edges[k].next)
		{
			if(!bvis[Edges[k].to])
			{
				que.push(Edges[k].to);
				bvis[Edges[k].to] = true;	
			}	
		}	
	} 
}

int main()
{
	int m,n;
	int i;
	int num1,num2,we;
	freopen("1.txt","r",stdin);
	scanf("%d%d",&m,&n); //m个点,n条边
	init();
	for(i=0;i<n;i++)
	{
		scanf("%d%d%d",&num1,&num2,&we);
		add(num1,num2,we);
	}
	printf("traver result:\n");		
	traver(m);
	printf("-------------------------------\n");
	printf("dfs result:\n");
	dfs(1);
	printf("-------------------------------\n");
	printf("bfs result:\n");
	bfs(1);
	return 0;
} 

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/u013021513/article/details/47453923
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞