試實現鄰接表存儲圖的廣度優先遍歷。
函數接口定義:
void BFS ( LGraph Graph, Vertex S, void (*Visit)(Vertex) );
其中LGraph
是鄰接表存儲的圖,定義如下:
/* 鄰接點的定義 */
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; /* 以鄰接表方式存儲的圖類型 */
函數BFS
應從第S
個頂點出發對鄰接表存儲的圖Graph
進行廣度優先搜索,遍歷時用裁判定義的函數Visit
訪問每個頂點。當訪問鄰接點時,要求按鄰接表順序訪問。題目保證S
是圖中的合法頂點。
裁判測試程序樣例:
#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 main() { LGraph G; Vertex S; G = CreateGraph(); scanf("%d", &S); printf("BFS from %d:", S); BFS(G, S, Visit); return 0; } /* 你的代碼將被嵌在這里 */
輸入樣例:給定圖如下
2
輸出樣例:
BFS from 2: 2 0 3 5 4 1 6
結尾無空行
廣度優先遍歷(BFS)需要用隊列,這里使用數組模擬隊列
void BFS(LGraph Graph, Vertex S, void (*Visit)(Vertex)) { Vertex queue[1010]; int l = 0, r = 0;//定義隊頭和隊尾 Visit(S); Visited[S] = true; queue[r++] = S;//將S入到隊尾 PtrToAdjVNode tmp; while (l != r)//當隊列不為空時 { tmp = Graph->G[queue[l++]].FirstEdge;//指向鄰接表頭的指針 while (tmp)//當指針不為空時 { if (!Visited[tmp->AdjV])//如果沒有被訪問過 { Visit(tmp->AdjV); Visited[tmp->AdjV] = true; queue[r++] = tmp->AdjV; } tmp = tmp->Next; } } }
放上圖片方便理解