数据结构 —— 图 之用邻接矩阵存储图

文章目录

代码

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

#define MAXVEX  100   //定义最大定点数
typedef int WeightType ;  //定义权重类型
typedef int DataType ;  //定义顶点数据类型

typedef struct GNode *PtrToGNode ;
struct GNode{
    int Ne;
    int Nv;
    WeightType G[MAXVEX][MAXVEX];
    DataType Data[MAXVEX];
};
typedef PtrToGNode MGraph;  //定义GNode类型的指针MGraph


typedef int Vertex;  //定义定点类型
MGraph CreateGraph(int vertexNum)
{
    Vertex V,W;  //V和W表示的是两个顶点  虽然也是int类型,但其本质上表示的是两个顶点
    MGraph MyGraph = new GNode;
    //MGraph MyGraph = (MGraph) malloc(sizeof(struct GNode));
    MyGraph->Ne = 0;
    MyGraph->Nv = vertexNum;
    //遍历顶点,给邻接矩阵做一个初始化为0的操作
    for(V=0;V<MyGraph->Nv;V++)
    {
        for(W=V;W<MyGraph->Nv;W++)
        {
            MyGraph->G[V][W] = 0;
            MyGraph->G[W][V] = 0;
        }
    }
    return MyGraph;
}

typedef struct ENode *PtrToENode;
//定义边  包含这个边连接的两个顶点和这条边对应的权重
struct ENode{
    Vertex v1,v2;
    WeightType w;
};
typedef PtrToENode Edge;

//在初始化之后的邻接矩阵中添加边
void InsertEdge(MGraph Graph,Edge E)
{
    Graph->G[E->v1][E->v2] = E->w;
    Graph->G[E->v1][E->v2] = E->w;
}



MGraph BuildGraph()
{
    //输入顶点个数,并根据顶点个数初始化邻接矩阵
    int num_vex;
    cout<<"Please input the num of vertex: ";
    cin>>num_vex;
    MGraph MyGraph = CreateGraph(num_vex);

    //输入边的个数。添加边
    cout<<endl<<"Please input the num of edge: ";
    cin>>MyGraph->Ne;
    for(int i=0;i<MyGraph->Ne;i++)
    {
        Edge edge = new ENode;
        cout <<endl<< "Please input the edge (eg. vertex1,vertex2,wight )   num"<<i<<": ";
        cin >> edge->v1 >> edge->v2 >> edge->w;
        InsertEdge(MyGraph, edge);
        cout<<endl;
    }
    
    return MyGraph;
}

// cout运算符重载  输出邻接矩阵
ostream &operator<<(ostream &cout,MGraph Graph)
{
    if(Graph->Ne!=0)
    {
        Vertex V,W;
        for(V=0;V<Graph->Nv;V++)
        {
            for(W=0;W<Graph->Nv;W++)
            {
                cout<<setw(5)<<Graph->G[V][W];
            }
            cout<<endl;
        }
    } else{
        cout << "This graph has zero edge!" << endl;
    }
    return cout;
}

int main() {
    cout<<BuildGraph()<<endl;
    return 0;
}

输出

Please input the num of vertex:5
Please input the num of edge:3
Please input the edge (eg. vertex1,vertex2,wight )   num0: 0 1 21

Please input the edge (eg. vertex1,vertex2,wight )   num1: 1 4 32

Please input the edge (eg. vertex1,vertex2,wight )   num2: 2 3 23

    0   21    0    0    0
   21    0    0    0   32
    0    0    0   23    0
    0    0   23    0    0
    0   32    0    0    0


Process finished with exit code 0
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值