### 數據結構實驗 用鄰接矩陣實現圖的深度優先搜索DFS

Problem Description

Input

Output

Sample Input

6

3 6 5 4 9 8

6

3 6

3 4

5 9

3 5

9 8

3 8

Sample Output

3 6 5 4 9 8

3 0 1 1 1 0 1

6 1 0 0 0 0 0

5 1 0 0 0 1 0

4 1 0 0 0 0 0

9 0 0 1 0 0 1

8 1 0 0 0 1 0

`#include <iostream>#include <cstring>#include <string>using namespace std;/* * 名稱: 圖的遍歷 * 方法: 鄰接矩陣儲存+深度優先搜索進行遍歷(DFS) *  by : mazicwong * 專業: 軟件工程 *//*63 6 5 4 9 863 63 45 93 59 83 8*//*這里如果在前面用typedef char VERTYPE的話,后面的輸出不能用printf和scanf來控制只能夠用成cin , cout*///http://www.cnblogs.com/gentleming/archive/2010/08/06/1793903.htmlconst int MAX_VERTEX_NUM = 10;//最大頂點個數typedef char VERTYPE;typedef	struct {	VERTYPE vexs[MAX_VERTEX_NUM];//頂點向量	int visited[MAX_VERTEX_NUM];//標志訪問過的點	int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM];	int vexnum, arcnum;//當前頂點數和弧數}mgraph,*MGraph;void init_mgraph(MGraph &g)  //初始化圖{	g = (MGraph)malloc(sizeof(mgraph));	g->vexnum = g->arcnum = 0;	for (int i = 0; i < MAX_VERTEX_NUM; i++)		g->vexs[i] = 0;  //頂點數組初始化	for (int i = 0; i < MAX_VERTEX_NUM; i++)		g->visited[i] = 0;  //標記數組初始化	for (int i = 0; i < MAX_VERTEX_NUM; i++)		for (int j = 0; j < MAX_VERTEX_NUM; j++)			g->arcs[i][j] = 0;//鄰接矩陣初始化}void add_vexs(MGraph &g)  //增加點{	printf("請輸入頂點個數\n");	scanf("%d%*c", &g->vexnum);	printf("請輸入頂點的值\n");	for (int i = 0; i < g->vexnum; i++)		scanf("%c%*c", &g->vexs[i]);}void add_arcs(MGraph &g)  //增加邊{	printf("請輸入邊的個數\n");	scanf("%d", &g->arcnum);	VERTYPE ch1, ch2;	int row, col;	printf("請輸入每條邊的端點\n");	for (int i = 0; i < g->arcnum; i++)	{		getchar();		scanf("%c %c", &ch1, &ch2);		for (int j = 0; j < g->arcnum; j++)  //找到那條邊的兩個點進行賦值		{			if (g->vexs[j] == ch1)				row = j;			if (g->vexs[j] == ch2)				col = j;		}		g->arcs[row][col] = 1;		g->arcs[col][row] = 1;//行和列在無向圖的鄰接矩陣是對稱的,要加這一行			}}void creat_mgraph(MGraph &g){	add_vexs(g);	add_arcs(g);}void print_mgraph(MGraph &g){	printf("輸出鄰接矩陣:\n ");	for (int i = 0; i < g->vexnum; i++)		cout << " " << g->vexs[i];	puts("");	for (int i = 0; i < g->vexnum; i++)	{		printf("%c ", g->vexs[i]);		for (int j = 0; j < g->vexnum; j++)			printf("%d ", g->arcs[i][j]);		puts("");	}}void visit(MGraph &g, int i){	printf("%c ", g->vexs[i]);	g->visited[i] = 1;}void DFSTraverse(MGraph &g, int i)  //從第i個頂點開始搜素{	visit(g, i);	for (int j = 0; j < g->vexnum; j++)	{		if (g->arcs[i][j] && !g->visited[j])			DFSTraverse(g, j);	}}int main(){	MGraph G;	init_mgraph(G);	creat_mgraph(G);	print_mgraph(G);	printf("圖的DFS遍歷結果: ");	DFSTraverse(G, 0);	return 0;}`