数据结构与算法(C语言版)__邻接矩阵

图,包含顶点和边,在C++里面可以用类来表示

邻接矩阵吧图转化为二维矩阵,当图比较稀疏时可以用邻接表。

这里写图片描述

#include<iostream>

#define MAX_VERTS 20

using namespace std;

class Vertex{
public:
    Vertex(char label){ Label = label; }
private:
    char Label;
};

class Graph{
public:
    Graph();
    ~Graph();
    void addVertex(char lab);
    void addEdge(int start, int end);
    void printMatrix();
private:
    Vertex* vertexList[MAX_VERTS];
    int nVerts;//顶点个数
    int adjMat[MAX_VERTS][MAX_VERTS];
};

Graph::Graph(){
    nVerts = 0;
    for (int i = 0; i < MAX_VERTS; i++){
        for (int j = 0; j < MAX_VERTS; j++){
            adjMat[i][j] = 0;
        }
    }
}

void Graph::addVertex(char lab){
    vertexList[nVerts++] = new Vertex(lab);
}

void Graph::addEdge(int start, int end){
    adjMat[start][end] = 1;
    adjMat[end][start] = 1;
}

void Graph::printMatrix(){
    for (int i = 0; i < nVerts; i++){
        for (int j = 0; j < nVerts; j++){
            cout << adjMat[i][j] << " ";
        }
        cout << endl;
    }
}

Graph::~Graph(){
    for (int i = 0; i < nVerts; i++){
        delete vertexList[i];
    }
}
int main(){

    cout << "测试邻接矩阵:" << endl;

    Graph g;
    g.addVertex('A');//0
    g.addVertex('B');//1
    g.addVertex('C');//2
    g.addVertex('D');//3
    g.addVertex('E');//4

    g.addEdge(0, 1);
    g.addEdge(0, 3);
    g.addEdge(1, 0);
    g.addEdge(1, 4);
    g.addEdge(2, 4);
    g.addEdge(3, 0);
    g.addEdge(3, 4);
    g.addEdge(4, 1);
    g.addEdge(4, 2);
    g.addEdge(4, 3);

    g.printMatrix();

    system("pause");
    return 0;
}

总结:我们可以使用邻接矩阵表示图,但是当图比较稀疏时,邻接矩阵有很多零,这样就造成浪费,所以可以用邻接表来表示图。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值