#include <iostream>
#include <queue>
/**
*DFS usage:Refer to the hype data structure
*/
using namespace std;
#define maxvertex 100
typedef char vertextype; //vertex
typedef int Edgetype ; //edge
//define linklist node
typedef struct EdgeNode{
int adjvex ;//adjvex store the index of vertex
Edgetype weight;
struct EdgeNode *next; //list
}EdgeNode;
//define array which can be used to store the vertex
typedef struct VertexNode{
vertextype data;
EdgeNode* firstedge ;//Edge pointer
}VertexNode,Adjlist[maxvertex];
//define grapha which describe the numbers of vertex and edge
typedef struct {
Adjlist adjlist;
int numvertex,numedge;
}GraphAdjlist;
//establish the grapha
void CreateALGrapha(GraphAdjlist *G){
int i,j,k;
EdgeNode *e;
cout<<"input the numbers of vertex and edge:"<< endl;
cin>>G->numvertex>>G->numedge;
cout<<"input the information of vertex"<<endl;
for(i=0;i<G->numvertex;i++){
cin>>G->adjlist[i].data;
G->adjlist[i].firstedge=NULL;
}
for(k=0;k<G->numedge;k++){
//establish
cout<<"input (Vi,Vj) number:"<<endl;
cin>> i>>j;
e=(EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex=j; //index of adjvex
e->next=G->adjlist[i].firstedge;
G->adjlist[i].firstedge=e;
e=(EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex=i;
e->next=G->adjlist[j].firstedge;
G->adjlist[j].firstedge=e;
}
}
typedef int boollean;
boollean visited[maxvertex];
void BFSTraverse(GraphAdjlist GL) {
int i;
EdgeNode *p;
queue<int> Q;
for (i = 0; i < GL.numvertex; i++)
visited[i] = 0;
for (i = 0; i < GL.numvertex; i++) {
if (!visited[i]) {
visited[i] = 1;
cout << GL.adjlist[i].data<<" ";//打印顶点,也可以是其他操作
Q.push(i);
while (!Q.empty()) {
i = Q.front();
Q.pop();
p = GL.adjlist[i].firstedge;//找到当前顶点边表链表头指针
while (p) {
if (!visited[p->adjvex])//若此顶点未被访问
{
visited[p->adjvex] = 1;
cout << GL.adjlist[p->adjvex].data<<" ";
Q.push(p->adjvex);//将此顶点入队列
}
p = p->next;//指针指向下一个邻接点
}
}
}
}
}
int main() {
GraphAdjlist *GL = (GraphAdjlist*)malloc(sizeof(GraphAdjlist));
CreateALGrapha(GL);
BFSTraverse(*GL);
}