試實現鄰接矩陣存儲圖的深度優先遍歷。
函數接口定義:
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );
其中MGraph
是鄰接矩陣存儲的圖,定義如下:
typedef struct GNode *PtrToGNode; struct GNode{ int Nv; /* 頂點數 */ int Ne; /* 邊數 */ WeightType G[MaxVertexNum][MaxVertexNum]; /* 鄰接矩陣 */ }; typedef PtrToGNode MGraph; /* 以鄰接矩陣存儲的圖類型 */
函數DFS
應從第V
個頂點出發遞歸地深度優先遍歷圖Graph
,遍歷時用裁判定義的函數Visit
訪問每個頂點。當訪問鄰接點時,要求按序號遞增的順序。題目保證V
是圖中的合法頂點。
裁判測試程序樣例:
#include <stdio.h> typedef enum {false, true} bool; #define MaxVertexNum 10 /* 最大頂點數設為10 */ #define INFINITY 65535 /* ∞設為雙字節無符號整數的最大值65535*/ typedef int Vertex; /* 用頂點下標表示頂點,為整型 */ typedef int WeightType; /* 邊的權值設為整型 */ typedef struct GNode *PtrToGNode; struct GNode{ int Nv; /* 頂點數 */ int Ne; /* 邊數 */ WeightType G[MaxVertexNum][MaxVertexNum]; /* 鄰接矩陣 */ }; typedef PtrToGNode MGraph; /* 以鄰接矩陣存儲的圖類型 */ bool Visited[MaxVertexNum]; /* 頂點的訪問標記 */ MGraph CreateGraph(); /* 創建圖並且將Visited初始化為false;裁判實現,細節不表 */ void Visit( Vertex V ) { printf(" %d", V); } void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ); int main() { MGraph G; Vertex V; G = CreateGraph(); scanf("%d", &V); printf("DFS from %d:", V); DFS(G, V, Visit); return 0; } /* 你的代碼將被嵌在這里 */
輸入樣例:給定圖如下
5
輸出樣例:
DFS from 5: 5 1 3 0 2 4 6
代碼:
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ) { Visited[V] = true; Visit(V); for(int i = 0;i < Graph -> Nv;i ++) { if(Visited[i] || Graph -> G[V][i] == INFINITY) continue; DFS(Graph,i,Visit); } }