1. 程式人生 > >6-1 鄰接矩陣儲存圖的深度優先遍歷 (20 分)

6-1 鄰接矩陣儲存圖的深度優先遍歷 (20 分)

試實現鄰接矩陣儲存圖的深度優先遍歷。

函式介面定義:

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
MGraph CreateGraph()
{
    int Nv, i, VertexNum;
    int v1, v2;
    Vertex V, W ;
    MGraph Graph;
    scanf("%d", &VertexNum);
    Graph = (MGraph)malloc(sizeof(struct GNode));
    Graph->Nv = VertexNum;
    Graph->Ne = 0;
    for
(V = 0; V < Graph->Nv; V ++) { for(W = 0; W < Graph->Nv; W ++) { Graph->G[V][W] = INFINITY; } } scanf("%d", &Graph->Ne); if(Graph->Ne) { for(i = 0; i < Graph->Ne; i ++) { scanf("%d %d", &v1, &v2); Graph->G[v1][v2] = 1; Graph->G[v2][v1] = 1; } } return Graph; } void DFS( MGraph Graph, Vertex v, void (*Visit)(Vertex) ) { Visited[v]=true; Visit(v); for(int i=0; i<Graph->Nv; i++) { if(Graph->G[v][i]==1&&!Visited[i]) { DFS(Graph,i,Visit); } } }