图的邻接矩阵代码错误求助
在学习prim算法求最小生成树过程中,想按照用户输入“行数 列数 权重”的形式对邻接表进行初始化,但是写一般发现两个问题,一是用户赋值的for循环根本没执行,二是权值的最大值应该是100,代码输出竟然
你给你的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;
}