图实验题二:实现图的遍历算法

Posted sunbines

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图实验题二:实现图的遍历算法相关的知识,希望对你有一定的参考价值。

递归深度优先遍历算法

 1 #include<stdio.h>
 2 #include<malloc.h>
 3 #define MAXV 100
 4 #define INF 32767
 5 typedef struct ANode
 6 {
 7     int adjvex;
 8     int weight;
 9     struct ANode *nextarc;
10 } ArcNode;
11 
12 typedef struct
13 {
14     int count;
15     ArcNode *firstarc;
16 } VNode;
17 
18 typedef struct
19 {
20     VNode adjlist[MAXV];
21     int n, e;
22 }AdjGraph;
23 
24 int visit[MAXV] = { 0 };
25 
26 void CreateAdj(AdjGraph* &G, int A[MAXV][MAXV], int n, int e);
27 void DFS(AdjGraph *G, int v);
28 
29 int main()
30 {
31     AdjGraph * G;
32     int n = 6, e = 10;
33     int A[MAXV][MAXV] = { { 0, 5, INF, 7, INF, INF },
34     { INF, 0, 4, INF, INF, INF },{ 8, INF, 0, INF, INF, 9 },
35     { INF, INF, 5, 0, 5 },{ INF, INF, INF, 5, 0, INF },{ 3, INF, INF, INF, 1, 0 } };
36     CreateAdj(G, A, n, e);
37     printf("从0开始的DFS算法: ");
38     DFS(G, 0);
39     printf("\\n");
40     return 0;
41 }
42 
43 void DFS(AdjGraph *G, int v) //递归深度优先遍历算法
44 {
45     ArcNode *p;
46     printf("%d ", v);
47     visit[v] = 1;
48     p = G->adjlist[v].firstarc;
49     while (p != NULL)
50     {
51         if (visit[p->adjvex] == 0)
52             DFS(G, p->adjvex);
53         p = p->nextarc;
54     }
55 }
56 
57 void CreateAdj(AdjGraph* &G, int A[MAXV][MAXV], int n, int e)  //创建图的邻接表
58 {
59     ArcNode *p;
60     G = (AdjGraph*)malloc(sizeof(AdjGraph));
61     for (int i = 0; i < n; ++i)
62         G->adjlist[i].firstarc = NULL;
63     for (int i = 0; i < n; ++i)
64         for (int j = n - 1; j >= 0; --j)
65             if (A[i][j] != 0 && A[i][j] != INF)
66             {
67                 p = (ArcNode *)malloc(sizeof(ArcNode));
68                 p->weight = A[i][j];
69                 p->adjvex = j;
70                 p->nextarc = G->adjlist[i].firstarc;
71                 G->adjlist[i].firstarc = p;
72             }
73     G->n = n;
74     G->e = e;
75 }

运行结果:
技术分享图片

 

 

以上是关于图实验题二:实现图的遍历算法的主要内容,如果未能解决你的问题,请参考以下文章

数据结构实验报告-实验四 图的构造与遍历

图的各类算法实现

图的各类算法实现

数据结构 图的基本操作实现

C语言实现图的广度优先搜索遍历算法

Java实现图的深度和广度优先遍历算法