广度遍历有向图

问题:还是指针的问题,在第一次遍历时,一定要用一个临时指针来指向图节点,不然等遍历玩指针为空,再用广度遍历算法就会失效。

广度遍历类似于树层次遍历,只是有顺序,因此用到了队列。再次证明了STL的强大和方便。

代码:

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

#define MAXV 20

typedef struct edgeNode
{
	int data;
	struct edgeNode *next;
}edgeList;

typedef struct headNode
{
	char vex;
	edgeList *firstNode;
}headList;

typedef struct graph           //定义邻接表结构
{
	headList arr[MAXV];
	int v,e;
}*adjGraph;


void createAdjGraph(adjGraph &ag)
{
	char c;
	int p,q;
	edgeList *s;
	cout<<"please input the num of v and e:";
	cin>>ag->v>>ag->e;

	for(int i=0;i<ag->v;i++)             //初始化头节点
	{
		cout<<"please input vex:";
		cin>>c;
		ag->arr[i].vex=c;
		ag->arr[i].firstNode=NULL;
	}

	for(int j=0;j<ag->e;j++)
	{
		cout<<"please input two vexs:";
		cin>>p>>q;
		s=(edgeList *)malloc(sizeof(struct edgeNode));
		s->data=p;
		s->next=ag->arr[q].firstNode;
		ag->arr[q].firstNode=s;
	}
}

void showAdjGraph(adjGraph ag)
{
	edgeList* s;
	for(int i=0;i<ag->v;i++)
	{
		cout<<ag->arr[i].vex<<"  ";
		s=ag->arr[i].firstNode;
		while(s!=NULL)
		{
			cout<<s->data<<" ";
			s=s->next;
		}
		cout<<endl;
	}
	delete s;
}

void BFSTraveral(adjGraph ag)
{
	int visited[MAXV];
	int k;
	queue<int> q;
	edgeList *el;
	el=(edgeList*)malloc(sizeof(struct edgeNode));

	for(int i=0;i<ag->v;i++)
	{
		visited[i]=0;
	}

	for(int i=0;i<ag->v;i++)
	{
		if(visited[i]==0)
		{		
		visited[i]=1;
		cout<<ag->arr[i].vex<<"->";
		q.push(i);
		while(!q.empty())	
		{
			 k=q.front();	
			 q.pop();
			 el=ag->arr[k].firstNode;
			// cout<<"hello world";
			 while(el)
			 {	 
			  // cout<<"hello world";
			  if(visited[el->data]==0)
			  {
				  visited[el->data]=1;
				  cout<<ag->arr[el->data].vex<<"->";
			//	  cout<<"hello world";
				  q.push(el->data);
			  }
			  el=el->next;
			  
			 } 
			 cout<<endl;
		}
		}
		
	}
	free(el);
}


int main()
{
	adjGraph ag;
	ag=(adjGraph)malloc(sizeof(struct graph));
	cout<<"创建有向图:"<<endl;
	createAdjGraph(ag);
	cout<<"输出有向图"<<endl;
	showAdjGraph(ag);
	cout<<"广度遍历有向图:"<<endl;
	BFSTraveral(ag);
	return 0;
}

 运行截图:

转载于:https://www.cnblogs.com/xshang/archive/2013/05/11/3072421.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值