6-2 圖的深度遍歷-鄰接表實現 (10 分)

本題要求實現鄰接表存儲圖的深度優先遍歷。

函數接口定義:


void DFS(ALGraph *G,int i);

其中ALGraph是鄰接表存儲的圖,定義如下:

#define MAX_VERTEX_NUM 10      /*定義最大頂點數*/
typedef int Vertex;
typedef struct  ArcNode{       /*表結點*/
	int adjvex;               /*鄰接點域*/
	struct  ArcNode *nextarc; /*指向下一個表結點*/
}ArcNode;
typedef struct VNode{           /*頭結點*/
	Vertex data;                  /*頂點域*/
	ArcNode *firstarc;          /*指向第一個表結點*/
}VNode,AdjList[MAX_VERTEX_NUM]; /*AdjList是數組類型*/
typedef struct { 
	AdjList vertices;           /*鄰接表中數組定義*/
	int vexnum,arcnum;          /*圖中當前頂點數和邊數*/
} ALGraph;                 /*圖類型*/

裁判測試程序樣例:


#include"stdio.h"
#include"stdlib.h"
#define MAX_VERTEX_NUM 10      /*定義最大頂點數*/
typedef int Vertex;
typedef struct  ArcNode{       /*表結點*/
	int adjvex;               /*鄰接點域*/
	struct  ArcNode *nextarc; /*指向下一個表結點*/
}ArcNode;
typedef struct VNode{           /*頭結點*/
	Vertex data;                  /*頂點域*/
	ArcNode *firstarc;          /*指向第一個表結點*/
}VNode,AdjList[MAX_VERTEX_NUM]; /*AdjList是數組類型*/
typedef struct { 
	AdjList vertices;           /*鄰接表中數組定義*/
	int vexnum,arcnum;          /*圖中當前頂點數和邊數*/
} ALGraph;                 /*圖類型*/
typedef enum{FALSE,TRUE} Boolean;
Boolean visited[MAX_VERTEX_NUM];/*定義標誌向量,爲全局變量*/
void CreatALGraph(ALGraph *G);/* 創建圖並且將Visited初始化爲false;裁判實現,細節不表 */
void DFS(ALGraph *G,int v);
int main()
{
	Vertex v;
	ALGraph G;
	CreatALGraph(&G);
	scanf("%d", &v);
	printf("DFS from %d:",v);
	DFS(&G,v); 	
	return 0;
}
/* 你的代碼將被嵌在這裏 */

對於給定圖:

圖的遍歷樣例.png

輸入樣例:

5

輸出樣例:

DFS from 5: 5 1 3 0 2 4 6
void DFS(ALGraph *G, int i) {
	printf(" %d",i);
	visited[i] = 1;
	struct  ArcNode * w;
	for ( w= G->vertices[i].firstarc;w;w=w->nextarc) {
		if (visited[w->adjvex] == 0)
			DFS(G, w->adjvex);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章