图的表示-邻接矩阵表示

描述

图的邻接矩阵(Adjacency Matrix)表示是采用二维数组的方式。通过邻接矩阵可以立刻看出两顶点之间是否存在一条边,只需要检查邻接矩阵重行i和列j是否是非零值。对于无向图,邻接矩阵是对称的。下图是摘自《算法:C语言实现》
这里写图片描述

代码实现

#include <iostream>
using namespace std;


const int VERTEX_NUM = 20;    // 顶点的最大数

typedef int graph_weight_t;   // 边的权值类型 可以为 int float double
typedef struct SArc
{
    graph_weight_t Weight;            // 权值
}AdjMatrix[VERTEX_NUM][VERTEX_NUM];   // 邻接矩阵

typedef struct SGraph
{
    int       iVertexNum;     // 顶点数
    int       iArcNum;        // 边数
    int       aVertex[VERTEX_NUM];  // 顶点向量
    AdjMatrix mArcs;          //邻接矩阵
}Graph;

void IintGraph(Graph &graph)
{
    //graph = (pGraph)malloc(sizeof(Graph));
    graph.iVertexNum = 0;
    graph.iArcNum    = 0;
    for(int i = 0; i < VERTEX_NUM; i++)
        graph.aVertex[i] = 0;
    for(int i = 0; i < VERTEX_NUM; i ++)
        for(int j= 0; j < VERTEX_NUM; j ++)
            graph.mArcs[i][j].Weight = 0;
}

void Add_Vertex(Graph &graph)
{
    cout << "Add Vertex" << endl;
    cout << "Input vertex number:";
    cin >> graph.iVertexNum;

    cout << "Input vertex value:";
    for(int i = 0; i < graph.iVertexNum; i ++)
        cin >> graph.aVertex[i];
}

int Locat_vertex(Graph &graph, int vertex)
{
    for(int i = 0; i < graph.iVertexNum; i ++)
    {
        if(graph.aVertex[i] == vertex)
            return i;
    }

    return -1;
}

void Add_Arcs(Graph &graph)
{
    cout << "Add Arcs" << endl;
    cout << "input arcs numbers:";
    cin >> graph.iArcNum;

    int   iFirst           = 0;
    int   iSecond          = 0;
    int   iRow             = 0;
    int   iCol             = 0;
    graph_weight_t iWeight  = 0;
    for(int i = 0; i < graph.iArcNum; i ++)
    {
        cout << "Input two Arc and Weight(ex. 1 2 32)" << endl;
        cin >> iFirst >> iSecond >> iWeight;

        iRow   =  Locat_vertex(graph, iFirst);
        iCol   =  Locat_vertex(graph, iSecond);

        graph.mArcs[iRow][iCol].Weight = iWeight;
        graph.mArcs[iCol][iRow].Weight = iWeight;
    }

}

void Creat_Graph(Graph &graph)
{
    cout << "Creat Graph" << endl;
    Add_Vertex(graph);
    Add_Arcs(graph);
}

void Show_Graph(Graph &graph)
{
    cout << "show the graph represented by adjmatrix "<<endl;

    for(int row = 0; row < graph.iVertexNum; row ++)
    {
        for(int col =0; col < graph.iVertexNum; col ++)
        {
            cout << graph.mArcs[row][col].Weight << "\t";
        }
        cout << endl;
    }

}

int main()
{
    Graph graph;
    IintGraph(graph);
    Creat_Graph(graph);
    Show_Graph(graph);
}

这里写图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值