采用邻接表表示图的深度优先搜索遍历

时间:2019-11-17
本文章向大家介绍采用邻接表表示图的深度优先搜索遍历,主要包括采用邻接表表示图的深度优先搜索遍历使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
//采用邻接表表示图的深度优先搜索遍历
#include <iostream>
using namespace std;

#define MVNum 100
typedef char VerTexType;

typedef char VerTexType;

typedef struct ArcNode {
    int adjvex;
    struct ArcNode* nextarc;
}ArcNode;

typedef struct VNode {
    VerTexType data;
    ArcNode* firstarc;
}VNode, AdjList[MVNum];

typedef struct {
    AdjList vertices;
    int vexnum, arcnum;
}ALGraph;

bool visited[MVNum];

int LocateVex(ALGraph G, VerTexType v) {
    for (int i = 0;i < G.vexnum;++i)
        if (G.vertices[i].data == v)
            return i;
    return -1;
}

void CreateUDG(ALGraph& G) {
    int i, k;
    cout << "请输入总顶点数,总边数,以空格隔开:";
    cin >> G.vexnum >> G.arcnum;
    cout << endl;

    cout << "输入点的名称,如a" << endl;

    for (i = 0;i < G.vexnum;++i) {
        cout << "请输入第" << (i + 1) << "个点的名称:";
        cin >> G.vertices[i].data;
        G.vertices[i].firstarc = NULL;
    }
    cout << endl;

    cout << "输入边依附的顶点,如a b" << endl;

    for (k = 0;k < G.arcnum;++k) {
        VerTexType v1, v2;
        int i, j;
        cout << "请输入第" << (k + 1) << "条边依附的顶点:";
        cin >> v1 >> v2;
        i = LocateVex(G, v1);
        j = LocateVex(G, v2);

        ArcNode* p1 = new ArcNode;
        p1->adjvex = j;
        p1->nextarc = G.vertices[j].firstarc;
        G.vertices[j].firstarc = p1;

        ArcNode* p2 = new ArcNode;
        p1->adjvex = j;
        p1->nextarc = G.vertices[j].firstarc;
        G.vertices[j].firstarc = p2;
    }
}

void DFS(ALGraph G, int v) {
    cout << G.vertices[v].data << "   ";
    visited[v] = true;
    ArcNode* p = G.vertices[v].firstarc;
    while (p != NULL) {
        int w = p->adjvex;
        if (!visited[w]) DFS(G, w);
        p = p->nextarc;
    }
}

int main() {
    cout << "采用邻接表表示图的深度优先搜索遍历";
    ALGraph G;
    CreateUDG(G);
    cout << endl;
    cout << "无向连通图G创建完成!" << endl;

    cout << "请输入其实的点";
    VerTexType c;
    cin >> c;

    int i;
    for (i = 0;i < G.vexnum;++i) {
        if (c == G.vertices[i].data)
            break;
    }
    cout << endl;
    while (i >= G.vexnum) {
        cout << "该点不存在,请重新输入!" << endl;
        cout << "请输入遍历连通图的起始点:";
        cin >> c;
        for (i = 0;i < G.vexnum;++i) {
            if (c == G.vertices[i].data)
                break;
        }
    }
    cout << "深度优先搜索遍历图结果:" << endl;
    DFS(G, i);

    cout << endl;
    return 0;
}

原文地址:https://www.cnblogs.com/ygjzs/p/11877601.html