C中具有邻接矩阵的图 [英] Graph with adjacency matrix in C

查看:134
本文介绍了C中具有邻接矩阵的图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个struct:

struct graph {
    int** adj; /**< Adjacency matrix. */
    int n; /**< Number of nodes in graph. */
};

我必须在此函数中创建一个空图:

and I have to create a void graph into this function:

struct graph *graph_create(int nodes) {
  //To implement
}

如何使用该双指针int** adj创建矩阵?

How can I create a matrix using that double pointer int** adj?

推荐答案

以下是使用malloc()定义矩阵的方法 我是从 GeeksForGeeks 捕获的.

Here is the way to define a matrix with malloc() that i catch from GeeksForGeeks with some edition.

具有int **malloc()

2D integer Matrix with int ** and malloc()

int r = 3, c = 4, i, j, count;

//arr[r][c]
int **arr = (int **)malloc(r * sizeof(int *));

for (i=0; i<r; i++){
    *(arr +i) = (int *)malloc(c * sizeof(int));
    //arr[i] = (int *)malloc(c * sizeof(int));
}

// Note that arr[i][j] is same as *(*(arr+i)+j)
count = 0;
for (i = 0; i <  r; i++)//3
    for (j = 0; j < c; j++)//4
        arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count

for (i = 0; i <  r; i++){
    printf("\n");
    for (j = 0; j < c; j++){
        printf("%d ", arr[i][j]);
    }
}

我们可以将这些代码放入graph_create(int nodes)函数中.

And we can put these code inside graph_create(int nodes) function.

代码

struct graph {
    int** adj; /**< Adjacency matrix. */
    int n; /**< Number of nodes in graph. */
}G;


struct graph *graph_create(int nodes) {

    struct graph * tmp = &G;
    int r = nodes, c = nodes, i, j, count;

    //arr[r][c]
    G.adj = (int **)malloc(r * sizeof(int *));

    for (i=0; i<r; i++){
         *(G.adj + i) = (int *)malloc(c * sizeof(int));
         //arr[i] = (int *)malloc(c * sizeof(int));
    }


    count = 0;
    for (i = 0; i <  r; i++)//3
      for (j = 0; j < c; j++)//4
         G.adj[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count

    for (i = 0; i <  r; i++){
        printf("\n");
        for (j = 0; j < c; j++){
            printf("%d ", G.adj[i][j]);
        }
    }

    return tmp;

}



int main()
{


    struct graph * d = graph_create(5);

    printf("\n");
    return 0;
}

我们知道图的邻接矩阵具有n * n维. 为此,我们将节点用作行和列.

We know the adjacency Matrix of a graph have n*n dimension. for that we use nodes as row and column.

修改

为了安全地使用malloc()函数,我们必须通过使用这些块调用free()来释放malloc()保留的存储位置. (类似于 Mobius 答案)

For secure working with malloc() function we must free the memory locations that is reserved by malloc(), by calling free() with these blocks. (similar to Mobius answer)

恰好在main()中的return 0;语句之前调用此:

just before return 0; statement in main() call this:

free ((*d).adj);

必需的头文件:

#include <stdio.h>
#include <stdlib.h> // for** malloc()**, **free()**

这篇关于C中具有邻接矩阵的图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆