数据结构学习笔记(四) 图之邻接表实现深度优先遍历

一下是使用邻接表存储表示,实现图的深度优先遍历的示例。
用于遍历的有向图如下:
《数据结构学习笔记(四) 图之邻接表实现深度优先遍历》

#include<iostream>
#define MaxVertexNum 6
using namespace std;
//抽象数据类型
typedef char vertextype;
//边结点类型
typedef struct edge
{
    int mark;
    int no;
    struct edge *next;
}edgetype;
//点结点类型
typedef struct
{
    int mark;
    vertextype vertex;
    edgetype *firstArc;
}vertexNode;
//图
typedef struct
{
    vertexNode vex[MaxVertexNum];
    int n,e;
}ALGraph;
ALGraph G;
edgetype *p;//用于遍历边结点

//构造有向图出边表
void create()
{
    G.n=6;

    G.vex[0].vertex='a';
    G.vex[1].vertex='b';
    G.vex[2].vertex='c';
    G.vex[3].vertex='d';
    G.vex[4].vertex='e';
    G.vex[5].vertex='f';

    G.vex[0].mark=G.vex[1].mark=G.vex[2].mark=G.vex[3].mark=G.vex[4].mark=G.vex[5].mark=0;

    edgetype *e1=new edgetype;
    edgetype *e2=new edgetype;
    edgetype *e3=new edgetype;
    edgetype *e4=new edgetype;
    edgetype *e5=new edgetype;
    edgetype *e6=new edgetype;
    edgetype *e7=new edgetype;
    edgetype *e8=new edgetype;
    edgetype *e9=new edgetype;
    edgetype *e10=new edgetype;

    e1->mark=e2->mark=e3->mark=e4->mark=e5->mark=0;
    e6->mark=e7->mark=e8->mark=e9->mark=e10->mark=0;

    e1->no=1;
    e2->no=4;
    e3->no=5;
    e4->no=5;
    e5->no=1;
    e6->no=2;
    e7->no=3;
    e8->no=5;
    e9->no=2;
    e10->no=3;

    G.vex[0].firstArc=e1;
    e1->next=e2;
    e2->next=e3;
    e3->next=NULL;

    G.vex[1].firstArc=e4;
    e4->next=NULL;

    G.vex[2].firstArc=e5;
    e5->next=NULL;

    G.vex[3].firstArc=e6;
    e6->next=NULL;

    G.vex[4].firstArc=e7;
    e7->next=e8;
    e8->next=NULL;

    G.vex[5].firstArc=e9;
    e9->next=e10;
    e10->next=NULL;
}

//图的深度优先遍历
void DFS(ALGraph &G,int i)
{
    edgetype *p;
    G.vex[i].mark=1;
    //cout<<G.vex[i].vertex;
    p=G.vex[i].firstArc;
    while(p!=NULL)
    {
        if(G.vex[p->no].mark==0)
        {
            p->mark=1;
            cout<<'('<<G.vex[i].vertex<<','<<G.vex[p->no].vertex<<')';
            DFS(G,p->no);
        }
        p=p->next;
    }
}

//深度优先遍历图的算法
void DFS_Component(ALGraph &G)
{
    int i;
    for(i=0;i<G.n;i++)
        if(G.vex[i].mark==0)
            DFS(G,i);
    cout<<endl;
}

//测试函数
int main()
{
    create();
    DFS_Component(G);
    return 0;
}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/Clementina_123/article/details/79204032
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞