#include <stdio.h> |
typedef enum { false , true } bool ; |
#define MaxVertexNum 10 /* 最大顶点数设为10 */ |
typedef int Vertex; /* 用顶点下标表示顶点,为整型 */ |
/* 邻接点的定义 */ |
typedef struct AdjVNode *PtrToAdjVNode; |
struct AdjVNode{ |
Vertex AdjV; /* 邻接点下标 */ |
PtrToAdjVNode Next; /* 指向下一个邻接点的指针 */ |
}; |
/* 顶点表头结点的定义 */ |
typedef struct Vnode{ |
PtrToAdjVNode FirstEdge; /* 边表头指针 */ |
} AdjList[MaxVertexNum]; /* AdjList是邻接表类型 */ |
/* 图结点的定义 */ |
typedef struct GNode *PtrToGNode; |
struct GNode{ |
int Nv; /* 顶点数 */ |
int Ne; /* 边数 */ |
AdjList G; /* 邻接表 */ |
}; |
typedef PtrToGNode LGraph; /* 以邻接表方式存储的图类型 */ |
bool Visited[MaxVertexNum]; /* 顶点的访问标记 */ |
LGraph CreateGraph(); /* 创建图并且将Visited初始化为false;裁判实现,细节不表 */ |
void Visit( Vertex V ) |
{ |
printf ( " %d" , V); |
} |
void BFS ( LGraph Graph, Vertex S, void (*Visit)(Vertex) ) |
{ |
int q[1010]; //模拟队列 |
int f = 0 , s = 0 ; //定义一前一后下标指针 |
(*Visit)(S); //访问S |
Visited[S] = 1; //设置Visited[S]的值为1 |
q[s++] = S; //将S入队 |
PtrToAdjVNode tmp; |
while ( f != s ) |
{ |
tmp = Graph->G[q[f++]].FirstEdge; |
while (tmp) |
{ |
Vertex pos = tmp->AdjV; |
if (!Visited[pos]) //若pos位置尚未被访问 |
{ |
Visit(pos); //访问pos |
Visited[pos] = 1; //更改pos位置为已被访问的 |
q[s++] = pos; //pos入队 |
} |
tmp = tmp->Next; //邻接表下一个就是它的兄弟 |
} |
} |
} |
int main() |
{ |
LGraph G; |
Vertex S; |
G = CreateGraph(); |
scanf ( "%d" , &S); |
printf ( "BFS from %d:" , S); |
BFS(G, S, Visit); |
return 0; |
} |