#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MaxVertexNum 100
#define INFINITY 65535
typedef int Vertex;
typedef struct ENode *PtrToENode;
struct ENode{
Vertex V1,V2;
int Weight;
};
typedef PtrToENode Edge;
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
int Weight;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
int Data;
}AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
bool Visited[MaxVertexNum];
LGraph CreateGraph()
{
int i, k, VertexNum;
Vertex V, E1, E2;
LGraph Graph;
scanf("%d", &VertexNum);
Graph = (LGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for(V = 0; V < Graph->Nv; V ++) {
Graph->G[V].FirstEdge = NULL;
}
scanf(" %d", &(Graph->Ne));
if(Graph->Ne) {
for(i = 0; i < Graph->Ne; i ++) {
scanf("%d %d", &E1, &E2);
PtrToAdjVNode NewNode;
NewNode = (PtrToAdjVNode)malloc (sizeof(struct AdjVNode));
NewNode->AdjV = E2;
NewNode->Next = Graph->G[E1].FirstEdge;
Graph->G[E1].FirstEdge = NewNode;
NewNode = (PtrToAdjVNode)malloc (sizeof(struct AdjVNode));
NewNode->AdjV = E1;
NewNode->Next = Graph->G[E2].FirstEdge;
Graph->G[E2].FirstEdge = NewNode;
}
}
return Graph;
}
void visit(LGraph Graph)
{
int i;
PtrToAdjVNode H;
for(i = 0; i < Graph->Nv; i ++){
printf("%d ",i);
H=Graph->G[i].FirstEdge;
while(H){
printf("%d ",H->AdjV);
H = H->Next;
}
printf("\n");
}
printf("\n");
}
void Visit( Vertex V )
{
printf("%d ",V);
}
void BFS ( LGraph Graph, Vertex S, void (*Visit)(Vertex) )
{
int queue[100];
int l = 0, r = 0;
queue[r++] = S;
Visit(S);
Visited[S] = true;
PtrToAdjVNode tmp;
while(l != r)
{
tmp = Graph->G[queue[l++]].FirstEdge;
while(tmp)
{
Vertex pos = tmp->AdjV;
if(!Visited[pos])
{
Visit(pos);
Visited[pos] = true;
queue[r++] = pos;
}
tmp = tmp->Next;
}
}
}
int main()
{
LGraph Graph;
LGraph G;
Vertex S=0;
G = CreateGraph();
visit(G);
BFS(G, S, Visit);
return 0;
}
GXU.OJ.6-2