图的邻接表存储以及深度和广度遍历

#include <iostream>
#include <queue>


using namespace std;
struct ArcNode
{
    int adjvec;//邻接点域
    ArcNode *next;
};


struct VertextNode//定义顶点表节点
{
    int vertex;
    int visited;
    ArcNode *firstedge;
};
#define MaxSize 10
typedef struct{
    VertextNode adjlist[MaxSize];//顶点表
    int vertexNum, arcNum;//图的顶点数和边数
}ALGraph;


ALGraph GreatALGraph(int a[],int n, int e)//邻接表的构造
{
    ALGraph G;
    G.vertexNum = n;
    G.arcNum = e;
    for(int i = 0; i < G.vertexNum; i++)//输入顶点信息,初始化顶点表
    {
        G.adjlist[i].vertex = a[i];
        G.adjlist[i].firstedge = NULL;
        G.adjlist[i].visited = 0;
    }


    for(int k = 0;k < G.arcNum; k++)
    {
        int i; int j;
        cin>>i>>j;
        ArcNode* s=new ArcNode;//(ArcNode*)malloc(sizeof(ArcNode));
        s->adjvec = j;
        s->next = G.adjlist[i].firstedge;
        G.adjlist[i].firstedge = s;
    }
    return G;
};


void DFC(ALGraph &G,int v)//深度优先
{
    cout<<G.adjlist[v].vertex;
    ArcNode*p =G.adjlist[v].firstedge;
    while(p!=NULL)
    {
        int j;
        j=p->adjvec;
        if(G.adjlist[j].visited==0)
        {


            G.adjlist[j].visited=1;
            p=p->next;
            DFC(G,j);
        }
        else{
            p=p->next;
        }
    }
}


void DFSTraverse(ALGraph &G)
{
    for(int j = 0; j < G.vertexNum; j++)
    {
        if((G.adjlist[j].visited == 0))
        {
            //cout<<" "<<j<<endl;
            G.adjlist[j].visited = 1;
            DFC(G,j);
        }
    }
}


void BFS(ALGraph &G, int v)//广度优先
{
    queue<int> a;
    cout<<G.adjlist[v].vertex;
    G.adjlist[v].visited = 1;
    a.push(v);
    while(!a.empty())
    {
//        v = G.adjlist[x].firstedge->adjvec;
        ArcNode *p = new ArcNode;
        p = G.adjlist[v].firstedge;
        while(p!=NULL)
        {
            if(G.adjlist[p->adjvec].visited == 0)//判断是否访问过
            {
                cout<<G.adjlist[p->adjvec].vertex;
                G.adjlist[p->adjvec].visited = 1;
                a.push(p->adjvec);
            }
            p=p->next;
        }
        a.pop();
        v = a.front();
    }
}


void BFSTraverse(ALGraph &G)
{
    for(int j = 0; j < G.vertexNum; j++)
    {
        if((G.adjlist[j].visited == 0))
        {
            //cout<<" "<<j<<endl;
            G.adjlist[j].visited = 1;
            BFS(G,j);
        }
    }
}




int main()
{
    ALGraph g;
    int a[8];
    for(int i = 0; i < 8; i++)
    {
        a[i] = i+1;
    }
    cout<<请输入点数;
    cin>>m;
    cout<<请输入边数;
    cin>>n;
    g = GreatALGraph(a,m,n);
    ALGraph h = g;
    //DFSTraverse(g);
    BFSTraverse(h);
    cout << "Hello world!" << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值