图的邻接矩阵代码错误求助

在学习prim算法求最小生成树过程中,想按照用户输入“行数 列数 权重”的形式对邻接表进行初始化,但是写一般发现两个问题,一是用户赋值的for循环根本没执行,二是权值的最大值应该是100,代码输出竟然是相当大的数

#include<iostream>
using namespace std;

#define MAX_VEX 20              //邻接表的最大边长
#define ARC_INFINITY  100  //权值的无限值,以65535代替

//定义无向图
class MGraph
{
public:
    char vertex;        //顶点
    int arc[MAX_VEX][MAX_VEX];      //邻接矩阵
    int numVertex,numArc;       //顶点数 边数
    MGraph(int numVertex,int numArc)
    {      
        this->numVertex = numVertex;
        this->numArc = numArc;
    }
};

//创建无向图
void Init_Mgraph(MGraph &G)
{
    int i,j,weight,n;
    // cout<<"please input the number of vertex and arc sparate with space key "<<endl;
    // cin>>G.numVertex>>G.numArc;

    //初始化邻接数组
    cout<<"numVertex: "<<G.numVertex<<"\t"<<"numArc: "<<G.numArc<<endl;
    for(i=0;i<G.numVertex;i++)
    {
        for(j=0;j<G.numVertex;j++)
        {
            if(i==j)
            {
                G.numArc = 0;
            }
            else
            {
                G.numArc = ARC_INFINITY;
            }
        }
    }

    //用户输入边的权值对邻接数组进行初始化
    cout<<"please input arc like: 0 1 13 "<<endl;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!这个循环没执行
    for(n=0;n<G.numArc;n++)
    {

        cout<<"input NO."<<n+1<<" arc"<<endl;
        cin>>i>>j>>weight;
        G.arc[i][j] = weight;
    }

    for(i=0;i<G.numVertex;i++)
    {
        for(j=0;j<G.numVertex;j++)
        {
            G.arc[i][j] = G.arc[j][i];  //无向图的邻接矩阵是对称的
        }
    }

    //对邻接矩阵进行输出验证
    for(i=0;i<G.numVertex;i++)
    {
        for(j=0;j<G.numVertex;j++)
        {
            cout<<G.arc[i][j]<<"\t\t";
        }
        cout<<endl;
    }
}


int main()
{
    MGraph G1(5,4);
    Init_Mgraph(G1);

    system("pause");
    return 0;
}
219 views
Comments
登录后评论
Sign In
·

你给你的G.numArc赋值了0或INF,我想应该是G.arc,你没赋值就遍历数组里面就是垃圾值

然后我还改进了一下你的代码

#include<iostream>

const int MAX_VEX = 20;
const int ARC_INFINITY = 100;

class MGraph{
public:
    int numVertex, numArc;
    int arc[MAX_VEX][MAX_VEX];
    char vertex;
    MGraph(int numVertex, int numArc, char vertex='?') 
        :numVertex(numVertex), numArc(numArc), vertex(vertex) {
        for (int i = 0; i < numVertex; i++)
            for (int j = 0; j < numVertex; j++)
                arc[i][j] = i == j ? 0 : ARC_INFINITY;
    }
};

void Init_Mgraph(MGraph& G)
{
    std::cout << "numVertex: " << G.numVertex << "\tnumArc: " << G.numArc << std::endl;
    std::cout << "please input arc like: 0 1 13 \n";
    for (int i = 0; i < G.numArc; i++){
        int m, n, weight;
        std::cout << "input NO." << i + 1 << " arc\n";
        std::cin >> m >> n >> weight;
        G.arc[m][n] = G.arc[n][m] = weight;
    }

    for (int i = 0; i < G.numVertex; i++){
        for (int j = 0; j < G.numVertex; j++)
            std::cout << G.arc[i][j] << "\t\t";
        std::cout << std::endl;
    }
}


int main()
{
    MGraph G1(5, 4);
    Init_Mgraph(G1);
    return 0;
}