简单的图邻接矩阵表示

#include<iostream>
using namespace std;
#define MaxNode 30
#define MaxEdge 40
class Graph1
{
      private:
              int a[30];        //顶点表
              int b[MaxNode][MaxNode];      //邻接矩阵
              int numnode,numedge,maxnode;
      public:
              Graph1(int sz=MaxNode);
              ~Graph1() { delete a; delete b;}         //delete的用法,删除new??
              int GetValue(int i);           //取第i个顶点的值
              int GetWeight(int x,int y);       //取两点间的权值
              int GetFirstNeighbor(int i);         //取顶点i的第一个邻接顶点
              int GetNextNeighbor(int x,int y);     //取顶点x的邻接顶点的下一个邻接顶点
              bool InsertNode(int i);              //插入顶点 
              bool InsertEdge(int x,int y,int edge);         //插入xy边
              bool display();
};
Graph1::Graph1(int sz)
{ 
       maxnode=sz; 
       // new 开辟数组时开辟的是指针 
       int i,j;
       for(i=0;i<maxnode;++i)
       for(j=0;j<maxnode;++j)
       b[i][j]=0;
       for(int k=0;k<maxnode;++k)
       a[k]=0;
       numnode=0;numedge=0;
}
int Graph1::GetValue(int i)
{
       if(a[i]>0)
       return a[i];
       return 0;
}
int Graph1::GetWeight(int x,int y)
{
      if(b[x][y]>0&&x<maxnode&&y<maxnode)
      return b[x][y];
      return 0;
}
int Graph1::GetFirstNeighbor(int i)
{
      int j;
      for(j=0;j<maxnode;++j)
      if(b[i][j]>0&&i<maxnode)
      return j;
      return 0;
}
int Graph1::GetNextNeighbor(int x,int y)
{
      for(int k=y+1;k<maxnode;++k)
      if(b[x][k]>0)
      return k;
      return 0;
}
bool Graph1::InsertNode(int i)
{
    if(numnode==maxnode) return false;
    a[numnode++]=i;
    return true;
}
bool Graph1::InsertEdge(int x,int y,int edge)
{
     if(numedge<40&&numnode<maxnode-2)
     { b[x][y]=b[y][x]=edge; numedge++;} 
     return true;
     return false;
}          
bool Graph1::display()
{
     cout<<"图中的顶点数"<<numnode<<endl;
     cout<<"图中的边数"<<numedge<<endl;
     for(int i=0;i<numnode;i++)
     for(int j=0;j<numnode;++j)
     {
      if(b[a[i]][a[j]]>0)
      {
      int w=b[a[i]][a[j]];
      cout<<"顶点("<<a[i]<<","<<a[j]<<")"<<" 权值"<<w<<endl;
      }
     }
} 
int main()
{
    Graph1 G(10);
    int n;
    cout<<" 请输入顶点的个数"<<endl; 
    cin>>n;
    int k;
    cout<<"请输入顶点信息!"<<endl; 
    for(int i=0;i<n;++i)
    {
            cin>>k;
            G.InsertNode(k);
    }
    cout<<"请输入添加边的条数"<<endl;
    int num;
    cin>>num;
    cout<<"请输入边的信息,依次为顶点 顶点 权值"<<endl;
    int x,y,w;
    for(int j=0;j<num;++j)
    {
     cin>>x>>y>>w;
     G.InsertEdge(x,y,w);
    } 
    G.display();
    system("pause");
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值