基于邻接表的图的遍历

(1)建立一个邻接表存储的图;(2)输出图的邻接表;(3)输出各顶点的度(若是有向图,输出各顶点的入度、出度和度);(4)对图进行深度优先、广度优先遍历。【测试数据】(1)输入图的种类:2输入图的顶点数和边数:5 5输入各条边:0 1 0 3 1 2 2 3 2 4(2)输入图的种类:0输入图的顶点数和边数:3 4输入各条边:0 1 0 2 1 0 1 2#include <iostream>#include <malloc.h>#include &
摘要由CSDN通过智能技术生成

(1)建立一个邻接表存储的图;(2)输出图的邻接表;(3)输出各顶点的度(若是有向图,输出各顶点的入度、出度和度);(4)对图进行深度优先、广度优先遍历。
【测试数据】
(1)

在这里插入图片描述

输入图的种类:2
输入图的顶点数和边数:5 5
输入各条边:0 1 0 3 1 2 2 3 2 4

(2)

在这里插入图片描述

输入图的种类:0
输入图的顶点数和边数:3 4
输入各条边:0 1 0 2 1 0 1 2


#include <iostream>
#include <malloc.h>
#include <queue>
using namespace std;

#define VertexType int
#define MaxVertexNum 20         //最大顶点数

queue<int>Q;                    //辅助队列

enum GraphType {
   DG, UDG};       //DG表示有向图,UDG表示无向图

typedef struct ArcNode          //边结点
{
   
    int adjvex;                 //邻接点的下标
    struct ArcNode *nextarc;    //后继链指针
} ArcNode;

typedef struct VNode            //顶点结点
{
   
    VertexType data;            //顶点数据
    ArcNode *firstarc;          //边链头指针
} VNode, AdjList[MaxVertexNum];

typedef struct
{
   
    AdjList vertices;           //邻接表
    int vexnum,arcnum;          //顶点数和边数
    int kind;             //图种类标志
} ALGraph;

//建立有向图
void CreateDGGraph(ALGraph &G)
{
   
    //  cout<<0<<endl;
    int m, n;                   //边<Vm,Vn>的下标
    ArcNode *vm, *vn;           //构成边<Vm,Vn>的两个顶点
    cout << "请输入顶点数和边数:";
    cin >> G.vexnum >> G.arcnum;

    //获取顶点信息
    for(int i=0; i<G.vexnum; i++)
    {
   
        G.vertices[i].data=i;
        G.vertices[i].firstarc=NULL;
    }

    //建立邻接表,采用头插法
    for(int i=0; i<G.arcnum; i++)
    {
   
        cout << "请输入<Vi,Vj>的下标:";
        cin >> m >> n;
        vm=(ArcNode*)malloc(sizeof(ArcNode));
        vm->adjvex=n;

        vm->nextarc=NULL;
        if(G.vertices[m].firstarc==NULL)
        {
   
            vn=G.vertices[m].firstarc=vm;
        }
        else
        {
   
            vn=vn->nextarc=vm;
        }
    }
}

//建立无向图
void CreateUDGGraph(ALGraph &G)
{
   
    int m, n;              
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值