• C++实现图(邻接矩阵)


     1 #include<iostream>
     2 
     3 #define Max 20
     4 using namespace std;
     5 
     6 class Vertex
     7 {
     8 public:
     9     Vertex(char lab) {Label=lab;}
    10 private:
    11     char Label;
    12 };
    13 
    14 
    15 class Graph
    16 {
    17 
    18 public:
    19     Graph();//构造函数
    20     ~Graph();//析构函数
    21     void addVertex(char lab);//增加一个节点
    22     void addEdge(int start,int end);//增加一条边,起点到终点
    23     void printMatrix();//打印出矩阵
    24 private:
    25     Vertex* vertexList[Max];   //存放每个节点的指针的数组
    26     int nVerts;//实际数量
    27     int adjMat[Max][Max];//矩阵
    28 };
    29 Graph::Graph()
    30 {
    31 
    32     nVerts=0;
    33     for(int i=0;i<Max;i++)
    34         for(int j=0;j<Max;j++)
    35             adjMat[i][j]=0;
    36 
    37 }
    38 void Graph::addVertex(char lab)
    39 {
    40 
    41     vertexList[nVerts++]=new Vertex(lab);//
    42 
    43 }
    44 void Graph::addEdge(int start,int end)
    45 {
    46     adjMat[start][end]=adjMat[end][start]=1;
    47 
    48 }
    49 
    50 void Graph::printMatrix()
    51 {
    52 
    53     for(int i=0;i<nVerts;i++)
    54     {
    55         for(int j=0;j<nVerts;j++)
    56         {
    57             cout<<adjMat[i][j]<<" ";
    58         }
    59         cout<<endl;
    60     }
    61 }
    62 
    63 Graph::~Graph()
    64 {
    65 
    66     for(int i=0;i<nVerts;i++)
    67     {
    68         delete vertexList[i];
    69     }
    70 }
    71 int main()
    72 {
    73 
    74     Graph g;
    75     g.addVertex('A');//0
    76     g.addVertex('B');//1
    77     g.addVertex('C');//2
    78     g.addVertex('D');//3
    79     g.addVertex('E');//4
    80     g.addEdge(0,1);//A-B
    81     g.addEdge(1,4);//B-E
    82     g.addEdge(2,4);//C-E
    83 
    84     g.addEdge(0,3);//A-D
    85     g.addEdge(3,0);
    86     g.addEdge(3,4);
    87 
    88     g.printMatrix();
    89     return 0;
    90 }
  • 相关阅读:
    Winform 时间
    button的后台点击事件
    Winform文本框只能输入限定的文本
    vue的生命周期函数
    ES6新增语法
    购物车案例(JavaScript动态效果)
    前端es6总结
    jQuery与vue的区别是什么?
    vue实现双向绑定原理
    JS实现简单分页功能
  • 原文地址:https://www.cnblogs.com/libin123/p/10420211.html
Copyright © 2020-2023  润新知