天天看點

鄰接矩陣求頂點度

#include <iostream>//藍多多算法實驗六
#include<malloc.h>
using namespace std;
#define MAXVEX 100//最大頂點數
typedef char VertexType;//頂點類型
typedef int EdgeType;//邊的權值
typedef struct
{
    VertexType vexs[MAXVEX];//頂點表
    EdgeType edges[MAXVEX][MAXVEX];//鄰接矩陣
    int n, e;//頂點數和邊數   
}MGraph;
MGraph CreateMGraph(int pd)//建立鄰接矩陣
{
    MGraph G;
    int i, j, k, n;
    cout << "請輸入頂點數和邊數:";
    cin >> G.n >> G.e;
    cout << "請輸入頂點資訊:";
    for (i = 0; i < G.n; i++)
        cin >> G.vexs[i];
    for (i = 0; i < G.n; i++)
        for (j = 0; j < G.n; j++)
            G.edges[i][j] = 0;//初始化鄰接矩陣
    cout << "請輸入每條邊對應的兩個頂點的序号及權重:\n例:0 1 2 表示标注的第0個頂點和第1個頂點之間有邊且權重為2 (注意序号從0開始)\n";
    for (n = 0; n < G.e; n++)
    {
        cin >> i >> j >> k;//輸入邊的資訊
        G.edges[i][j] = k;
        if (pd == 0)//無向圖,邊是雙向的
            G.edges[j][i] = k;
    }
    return G;
}
void DisplayMGraph(MGraph G, int pd)//分行輸出
{
    for (int i = 0; i < G.n; i++)//第i個頂點(行)
    {
        cout << "第" << i + 1 << "行:";
        for (int j = 0; j < G.n; j++)//第j列
            if (pd == 0 && G.edges[i][j] == 0)
                cout << "∞" << "\t";
            else
                cout << G.edges[i][j] << "\t";
        cout << "\n";
    }
}
int OutDegree(MGraph G, int i)//(出)度(求第i個頂點表中的結點數)
{
    int degree = 0;
    for (int j = 0; j < G.n; j++)
        if (G.edges[i][j] != 0)
            degree++;
    return degree;
}
int InDegree(MGraph G, int i)//入度
{
    int degree = 0;
    for (int j = 0; j < G.n; j++)
        if (G.edges[j][i] != 0)
            degree++;
    return degree;
}
void PrintOut(MGraph G, int pd)//度
{
    int all;
    if (pd == 0)//無向圖
        for (int i = 0; i < G.n; i++)
            cout << "第" << i << "個頂點" << G.vexs[i] << "的度是" << OutDegree(G, i) << endl;
    else//有向圖
        for (int i = 0; i < G.n; i++)
        {
            cout << "第" << i << "個頂點" << G.vexs[i] << "的出度是" << OutDegree(G, i) << ",入度是" << InDegree(G, i) << endl;
            all = OutDegree(G, i) + InDegree(G, i);
            cout << "第" << i << "個頂點" << G.vexs[i] << "的度是" << all << endl;
        }
}
int main()
{
    //判斷是有向圖還是無向圖//
    cout << "如果是無向圖,請輸入0;如果是有向圖,請輸入1:";
    int pd;
    cin >> pd;
    if (pd != 0 && pd != 1)
    {
        cout << "輸入有誤,請退出重新輸入0或1。";
        return 0;
    }
    MGraph G = CreateMGraph(pd);
    cout << "\n分行輸出該鄰接矩陣為:\n";
    DisplayMGraph(G, pd);
    PrintOut(G, pd);
    system("pause");
    return 0;
}

      

繼續閱讀