图的遍历(邻接表实现)

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

typedef char DataType;
#define MAXV 10//最大顶点数
#define MAXE 50//最大边数
int visited[MAXV]={0};

typedef struct ArcNode{
    int adjvex;//邻接表
    ArcNode* next;
}ArcNode;

typedef struct VertexNode{
    DataType vertex;
    ArcNode*firstE;
}VertexNode;

typedef struct MyGraph{
VertexNode adjlist[MAXV];
    int VNum;
    int ENum;
}MyGraph;

void CreatGraph(MyGraph *G);
void DFS(MyGraph* G,int v);
void DFSTraverse(MyGraph *G);
void BFSTraverse(MyGraph* G,int v);

void CreatGraph(MyGraph *G)
{
    int i,j,k;
    cout<<"请输入图的顶点数和边数:"<<endl;
    cin>>G->VNum>>G->ENum;

    cout<<"请输入图的顶点信息:"<<endl;
    for(i=0;i<G->VNum;i++)//初始化顶点
    {
        cin>>G->adjlist[i].vertex;
        G->adjlist[i].firstE=NULL;
    }
    for(k=0;k<G->ENum;k++)
    {
        cout<<"请输入边所依附的两个顶点的编号:"<<endl;
        cin>>i>>j;

        ArcNode*s=new ArcNode; s->adjvex=j;
        s->next=G->adjlist[i].firstE;
        G->adjlist[i].firstE=s;
    }
}

void DFS(MyGraph *G,int v)
{
    ArcNode *p;
    int j;
    cout<<G->adjlist[v].vertex<<" "; visited[v]=1;
    p=G->adjlist[v].firstE;
    while(p!=NULL)
    {
        j=p->adjvex;
        if(visited[j]==0) DFS(G,j);
        p=p->next;
    }
}

void DFSTraverse(MyGraph* G)
{
    ArcNode *p;
    int i,j;
    for(i=0;i<G->VNum;i++) visited[i]=0;

    for(i=0;i<G->VNum;i++)
        {
            p=G->adjlist[i].firstE;
            if(p!=NULL&&visited[i]==0) DFS(G,i);
        }
}

void BFSTraverse(MyGraph* G,int v)
{
    int j;
    ArcNode *p;
    queue<int> q;
    cout<<G->adjlist[v].vertex<<" "; visited[v]=1;
    v=q.front();
    while(!q.empty())
    {
        p=G->adjlist[v].firstE;
        while(p!=NULL)
        {
            j=p->adjvex;
            if(visited[j]==0){
                cout<<G->adjlist[j].vertex;
                visited[j]=1;
                q.front()=j;
            }
        }
    }
}

int main()
{
    MyGraph* G=new MyGraph;
    CreatGraph(G);

    cout<<"该图的深度优先遍历顺序:"<<endl;
    DFSTraverse(G);
    cout<<endl;
    cout<<"该图的广度优先遍历顺序:"<<endl;
    for(int i=0;i<G->VNum;i++)
    BFSTraverse(G,i);

    return 0;

}

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