首页 > 其他分享 >7-1 邻接矩阵存储创建有向图

7-1 邻接矩阵存储创建有向图

时间:2022-11-13 19:47:50浏览次数:53  
标签:vexnum 存储 有向图 int ++ MVNum AMGraph 邻接矩阵 vnum

#include<iostream>
using namespace std;
#define MVNum 1000
typedef char VerTexType;
typedef int ArcType;
typedef struct 
{
    VerTexType vexs[MVNum];     //顶点
    ArcType arcs[MVNum][MVNum];  //边
    int vexnum,arcnum;          //顶点数和边数目
}AMGraph;

int LocateVex(AMGraph &G , VerTexType v)
{
    for(int i = 0 ; i < G.vexnum ; i++)
        if(G.vexs[i] == v)
            return i;
}

void CreateUDN(int vnum,int anum,AMGraph &G)
{
   G.vexnum = vnum;
   G.arcnum = anum;
    
    for(int i = 0 ; i < G.vexnum ; ++i)
        cin>>G.vexs[i];
    
    for(int i = 0 ; i<G.vexnum; ++i)
        for(int j = 0 ; j<G.vexnum; ++j)
            G.arcs[i][j] = 0;
    
    for(int k = 0 ; k < G.arcnum ; k++)
    {
        VerTexType v1,v2;
        cin>>v1>>v2;
        int i = LocateVex(G,v1);
        int j = LocateVex(G,v2);
        G.arcs[i][j] = 1;
    }
}

void show(AMGraph &G)
{
    for(int i = 0; i < G.vexnum ; i++)
    {
        for(int j = 0 ; j < G.vexnum; j++)
        {
            if(j == 3)
                 cout<<G.arcs[i][j];
            else
                 cout<<G.arcs[i][j]<<" ";
        }
        cout<<endl;
    }
}
int main()
{
    int vnum,anum;
    cin>>vnum>>anum;
    if(vnum == 0)
    {
        cout<<"error";
        return 0;
    } 
    if(vnum == 1 && anum > 0)
    {
        cout<<"error";
        return 0;
    }
    AMGraph G;
    CreateUDN(vnum,anum,G);
    show(G);
    return 0;
}

 

标签:vexnum,存储,有向图,int,++,MVNum,AMGraph,邻接矩阵,vnum
From: https://www.cnblogs.com/fan-wang/p/16886701.html

相关文章