fork download
  1. #include<stdlib.h>
  2. #include<stdio.h>
  3.  
  4. struct digraph //Estrutura do grafo, V e A são contadores, matrix_adj é um ponteiro para um array de ponteiros
  5. {
  6. int V , A;
  7. int **matrix_adj;
  8. };
  9.  
  10. typedef struct digraph* Digraph;
  11. int **matrix_alloc(int r,int c,int val);
  12. Digraph graph_alloc(int vertex);
  13. void insert(Digraph G, int v, int w);
  14. void show(Digraph G);
  15.  
  16. int main(void)
  17. {
  18. Digraph G;
  19. G = graph_alloc(6);
  20. insert(G, 1,2);
  21. insert(G, 1,3);
  22. insert(G, 2,4);
  23. insert(G, 3,4);
  24. insert(G, 4,5);
  25. insert(G, 5,6);
  26. show(G);
  27. return 0;
  28.  
  29. }
  30.  
  31. int **matrix_alloc(int r,int c,int val)
  32. {
  33. int i, j;
  34. int **matrix = (int**)malloc(r*sizeof(int*));// aloca linhas
  35. for(i=0;i<r;i++)
  36. {
  37. matrix[i] = (int*)malloc(c*sizeof(int));//aloca colunas
  38. for(j=0;j<c;j++)
  39. {
  40. matrix[i][j] = val;
  41. }
  42. }
  43. return matrix;
  44. }
  45.  
  46. Digraph graph_alloc(int vertex)
  47. {
  48. Digraph G = malloc(sizeof(struct digraph));
  49. G->V = vertex;
  50. G->A = 0;
  51. G->matrix_adj = matrix_alloc(vertex, vertex, 0);
  52. return G;
  53. }
  54.  
  55. void insert(Digraph G,int v, int w)
  56. {
  57. if(G->matrix_adj[v][w] == 0)
  58. {
  59. G->matrix_adj[v][w] = 1;
  60. G->matrix_adj[w][v] = 1;
  61. G->A++;
  62. }
  63. }
  64.  
  65. void show(Digraph G)
  66. {
  67. int v, w;
  68. for(v=0; v<G->V; v++)
  69. {
  70. for(w=0; w<G->V;w++)
  71. {
  72. printf("%d ", G->matrix_adj[v][w]);
  73. }
  74. printf("\n");
  75. }
  76. printf("\n");
  77. printf("Vertices: ", G->V);
  78. printf("Arestas: ", G->A);
  79. }
  80.  
Success #stdin #stdout 0s 4480KB
stdin
Standard input is empty
stdout
0 0 0 0 0 0 
0 0 1 1 0 0 
0 1 0 0 1 0 
0 1 0 0 1 0 
0 0 1 1 0 1 
0 0 0 0 1 0 

Vertices: Arestas: