6-16 鄰接表儲存圖的廣度優先遍歷
阿新 • • 發佈:2019-01-12
鄰接表儲存圖的廣度優先遍歷 (20 分)
試實現鄰接表儲存圖的廣度優先遍歷。
函式介面定義:
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
void BFS(LGraph Graph, Vertex S, void(*Visit)(Vertex)) {
Visited[S] = true; //先進行標記
int Queue[10000] ;
int front = 0;
int rear = 1;
Queue[0] = S; //建立佇列並初始化
while (front<rear){ //佇列不為空時進行
Visit(Queue[front]); //先訪問該節點
PtrToAdjVNode it = Graph->G[Queue[front]].FirstEdge; //然後把它為被訪問過的鄰接點入隊
while (it!=NULL){
if (!Visited[it->AdjV]){
Queue[rear++] = it->AdjV;
Visited[it->AdjV] = true;
}
it = it->Next;
}
front++;
}
return;
}