图---邻接矩阵

#include<iostream>
#include<stdlib.h>
#define MAX_VERTEX_NUM 20 //最大顶点数
using namespace std;

typedef char VertexType;   //顶点数据类型
typedef enum {DG, DN, UDG, UDN} GraphKind;
typedef struct
{
    int adj;   //权值
    int info;  //弧的相关信息
}ArcCell;

typedef struct {
    VertexType vex[MAX_VERTEX_NUM];      //顶点
    ArcCell arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //邻接矩阵
    int vexnum , arcnum;
    GraphKind kind;
}MGraph;

int LocateVex(MGraph *g , char v)
{
    for(int i = 0; i < g->vexnum; i++){
        if(g->vex[i] == v)
            return i;
    }
    return 0;
}

void CreateDG(MGraph *g)
{
    char v1, v2;
    int IncInfo;
    cout << "请输入顶点数与弧数以及弧的相关信息(1表示有信息,0表示无信息)" << endl;
    cin >> g->vexnum >> g->arcnum >> IncInfo;
    cout << "请输入顶点" << endl;
    for(int i = 0; i < g->vexnum; i++){
        cin >> g->vex[i];
    }
    
    for(int i = 0; i < g->vexnum; i++){
        for(int j = 0; j < g->vexnum; j++){
            g->arcs[i][j].adj = 0;
            g->arcs[i][j].info = 0;
            
        }
    }
    
    cout << "输入边所对应的顶点" << endl;
    
    for(int i = 0;i < g->arcnum; i++){
        cin >> v1 >> v2;
        int a = LocateVex(g, v1);
        int b = LocateVex(g, v2);
        g->arcs[a][b].adj = 1;
        if(IncInfo){
            int e;
            cin >> e;
            g->arcs[a][b].info = e;
        }
    }
    
}

void print(MGraph *g)
{
    cout << "邻接矩阵为:" << endl <<'\\' << " ";
    for(int i = 0; i < g->vexnum; i++){
        cout << g->vex[i] << " ";
    }
    cout << endl;
    for(int i = 0; i < g->vexnum; i++){
        cout << g->vex[i] << " ";
        for(int j = 0; j < g->vexnum; j++){
            cout << g->arcs[i][j].adj << " ";
        }
        cout << endl;
    }
}

int main()
{
    MGraph G;
    CreateDG(&G);
    print(&G);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhulmz/p/12070471.html