gpt4 book ai didi

c - C 中的图结构

转载 作者:行者123 更新时间:2023-11-30 16:38:44 26 4
gpt4 key购买 nike

我正在使用动态二维数组。

我想在结构中实现一个图表,这样我就可以像这样调用:

initialize(&costs);
initialize(&pred);

图结构为G = [ COSTS[1:n,1:n], pred[1:n, 1:n], n] 其中n是顶点数。

这就是我所拥有的:

#include <stdio.h>
#include <stdlib.h>

int main(){
int **matrix = NULL;
int n = 0;
int i, j;

scanf("%d", &n);

matrix = (int**)calloc(n, sizeof(int*));
// matrix is now an array of pointers to integers, which can be used as an array of integer arrays, hence a 2d matrix

for (i = 0; i < n; i++) {
// create an array for each ith element of matrix;
matrix[i] = (int*)calloc(n, sizeof(int));
}

for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
matrix[i][j] = 0; //initialize values
}
}
}

你能建议一下如何做吗?

最佳答案

所以你想要一个包含两个矩阵的结构?您也可以将 n 放入其中,因此它会类似于:

typedef struct {
int n;
int **cost;
int **pred;
} graph;

依次使用您在每个矩阵上编写的初始化代码。如果这是 C,则不要转换 malloc() 的返回值。

关于c - C 中的图结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47375202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com