图深度优先遍历的非递归实现

 采用非递归方法实现图的深度优先遍历

//
//  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;
}

 

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/Ian_Yan/article/details/82901493
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞