zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    SQL练习题
    数据库基础
    Java-反射与注解
    Linux基础
    pipeline的使用示例
    vagrant与vrtualbox的使用
    12.04公有,私有属性,析构函数,成员属性
    12.1面向对象编程的介绍(oop):封装,继承,多态,访问私有属性
    mysql操作之二:fetchone与获取lastrowid
    10.02经典类的bug
  • 原文地址:https://www.cnblogs.com/libin123/p/10420211.html
Copyright © 2011-2022 走看看