无向图的邻接矩阵是自然对称的,A-> B或B-> A的权重应该在矩阵中对称地表示。我已经实现了以下代码来生成图形的随机邻接矩阵,但事实证明它没有考虑这个属性。有人会建议我进行修改以使其有效吗?
#define INFTY INT_MAX
int **edge;
int N=5;
edge= malloc(N * sizeof(int *));
for (i = 0; i < N; i++)
{
edge[i] = malloc(N * sizeof(int));
}
srand(0);
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
if(i == j){
edge[i][j] = 0;
}
else{
int r = rand() % 10;
edge[i][j] = (r == 5)? INFTY: r;
}
}
}
答案 0 :(得分:2)
观察到无向图具有对称的邻接矩阵:
然后简单地随机分配矩阵的上三角形,并使下三角形匹配:
#define INFTY INT_MAX
int **edge;
int N=5;
edge= malloc(N * sizeof(int *));
for (i = 0; i < N; i++)
{
edge[i] = malloc(N * sizeof(int));
}
srand(0);
for(i = 0; i < N; i++)
{
for(j = i; j < N; j++)
{
if(i == j){
edge[i][j] = 0;
}
else{
int r = rand() % 10;
int val = (r == 5)? INFTY: r;
edge[i][j] = val;
edge[j][i] = val; // If there is edge from i to j, then there
// must be edge from j to i
}
}
}