无向图的邻接表描述和遍历

#include <iostream>     
#include <string>  
#include <queue>
using namespace std;    

typedef char vertexType;    //顶点的数据类型,这里姑且设为字符,A,B,C,D
#define MAXVEX 100  //最大顶点数
bool visited[MAXVEX];   //访问标记

struct edgeNode
{
    int adjvex;
    struct edgeNode* next;
};

typedef struct vertexNode
{
    vertexType data;
    edgeNode* firstEdge;
}AdjList[MAXVEX];

struct AdjListGraph   //图结构
{
    AdjList adjList;   //邻接表
    int numVertex, numEdge; //顶点数,边数
};

void createMGraph(AdjListGraph* G)
{
    edgeNode* e, *f;
    cout << "请输入顶点数,边数:";
    cin >> G->numVertex >> G->numEdge;
    cout << "请输入每个顶点的字母表示:";
    for (int i = 0; i < G->numVertex; i++)
    {
        cin >> G->adjList[i].data;
        G->adjList[i].firstEdge = nullptr;
    }
    cout << "请输入每条边的起点序号,终点序号:";
    for (int i = 0; i < G->numEdge; i++)
    {
        int start, end;
        cin >> start >> end;
        e = new edgeNode;
        e->adjvex = end;
        e->next = G->adjList[start].firstEdge;
        G->adjList[start].firstEdge = e;
        f = new edgeNode;
        f->adjvex = start;
        f->next = G->adjList[end].firstEdge;
        G->adjList[end].firstEdge = f;
    }
}

void DFS(AdjListGraph G, int i)
{
    visited[i] = true;
    edgeNode* p;
    cout << G.adjList[i].data << " ";
    p = G.adjList[i].firstEdge;
    while (p)
    {
        if (!visited[p->adjvex])
        {
            DFS(G, p->adjvex);
        }
        p = p->next;
    }
}

void DFSTraverse(AdjListGraph G)
{
    for (int i = 0; i < G.numVertex; i++)
    {
        visited[i] = false;
    }
    for (int i = 0; i < G.numVertex; i++)
    {
        if (!visited[i])
        {
            DFS(G, i);
        }
    }
}

void BFSTraverse(AdjListGraph G)
{
    queue<int> que;
    edgeNode* p;
    for (int i = 0; i < G.numVertex; i++)
    {
        visited[i] = false;
    }
    for (int i = 0; i < G.numVertex; i++)
    {
        if(!visited[i])
        {
            visited[i] = true;
            cout << G.adjList[i].data << " ";
            que.push(i);
            while(!que.empty())
            {
                int t = que.front();
                que.pop();
                p = G.adjList[t].firstEdge;
                while (p)
                {
                    if (!visited[p->adjvex])
                    {
                        visited[p->adjvex] = true;
                        cout << G.adjList[p->adjvex].data << " ";
                        que.push(p->adjvex);
                    }
                    p = p->next;
                }
            }
        }
    }
}

int main()    
{    
    AdjListGraph G;
    createMGraph(&G);
    cout << "DFS访问顶点顺序:   ";
    DFSTraverse(G);
    cout << endl;
    cout << "BFS访问顶点顺序:   ";
    BFSTraverse(G);
    cout << endl;
    return 0;  
}   

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