試實現鄰接矩陣存儲圖的深度優先遍歷。
函數接口定義:
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
作者: DS課程組
單位: 浙江大學
時間限制: 400 ms
內存限制: 64 MB
很明顯這個用遞歸就可以了
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ){
Visited[V] = true;
Visit(V);
//遞歸
int i;
for (i = 0; i<MaxVertexNum; i++) {
if (Graph->G[V][i] == 1 && !Visited[i]) {
DFS(Graph,i,Visit);
}
}
return;
}
根據提要求訪問過的節點需要true
所以在此訪問還應判斷該節點是不是false