圖深度優先遍歷的非遞迴實現
阿新 • • 發佈:2018-12-12
採用非遞迴方法實現圖的深度優先遍歷
// // GraphDFSNonRecursion.c // // // Created by yanbinbin // #include <stdio.h> #include <stdlib.h> #define maxSize 20 typedef struct ArcNode{ int adjvex; struct ArcNode *nextarc; }ArcNode; typedef struct{ char data; struct ArcNode *firstarc; }VNode; typedef struct{ VNode adjlist[maxSize]; int n, e; }AGraph; void createGraph(AGraph *G){ int i, tail, head, edges, vertex; ArcNode *tmp, *p; printf("請輸入圖的頂點數:"); scanf("%d", &vertex); printf("請輸入圖的邊數:"); scanf("%d", &edges); G->n = vertex; G->e = edges; for (i = 1; i <= edges; ++i) { printf("請輸入第%d條邊的弧尾與弧頭\n", i); printf("弧尾: "); scanf("%d", &tail); printf("弧頭: "); scanf("%d", &head); p = (ArcNode *)malloc(sizeof(ArcNode)); p->adjvex = head; p->nextarc = NULL; //建立鄰接表 tmp = G->adjlist[tail].firstarc; if(tmp == NULL) G->adjlist[tail].firstarc = p; else{ while (tmp->nextarc != NULL) tmp = tmp->nextarc; tmp->nextarc = p; } } printf("圖建立完畢\n"); } void DFSNonRecursion(AGraph *G, int v){ printf("圖DFS開始\n"); int stack[maxSize]; int top = -1; int visit[maxSize]; int i, j, k; ArcNode *p; for (i = 0; i < maxSize; ++i) visit[i] = 0; printf("%d ", v); visit[v] = 1; stack[++top] = v; while (top != -1) { j = stack[top]; p = G->adjlist[j].firstarc; while (p != NULL) { while (p != NULL && visit[p->adjvex] == 1) p = p->nextarc; if(p == NULL) break; k = p->adjvex; stack[++top] = k; visit[k] = 1; printf("%d ", k); p = G->adjlist[k].firstarc; } --top; } printf("\n圖DFS完畢\n"); } int main(){ AGraph G; createGraph(&G); DFSNonRecursion(&G, 0); return 0; }