递归深度优先遍历算法
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 }
运行结果:
原文地址:https://www.cnblogs.com/sunbines/p/8849583.html
时间: 2024-10-10 06:11:10