广度遍历有向图

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

广度遍历类似于树层次遍历,只是有顺序,因此用到了队列。再次证明了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;

}

 运行截图:

广度遍历有向图

广度遍历有向图

你可能感兴趣的:(遍历)