Advertisement
IcaroPeretti

MatrizADJ

Dec 1st, 2020
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Grafo{
  5.     int **A;
  6.     int n;
  7.     int m
  8. }Grafo;
  9.  
  10. Grafo* graphInit(int n)
  11. {
  12.     int i, j;
  13.     Grafo *grafo = (Grafo*)malloc(sizeof(Grafo));
  14.     grafo->n = n;
  15.     grafo->m = 0;
  16.     grafo->A = malloc(n * sizeof(int *));
  17.     for (i = 0; i < n; i++)
  18.     {
  19.         grafo->A[i] = malloc(n * sizeof(int));
  20.     }
  21.  
  22.     for (i = 0; i < n; i++)
  23.     {
  24.         for (j = 0; j < n; j++)
  25.         {
  26.             grafo->A[i][j] = 0;
  27.         }
  28.     }
  29.  
  30.     return grafo;
  31. }
  32.  
  33. void graphInsertArc(Grafo *G, int v, int w)
  34. {
  35.     if (G->A[v][w] == 0)
  36.     {
  37.         G->A[v][w] = 1;
  38.         G->m++;
  39.     }
  40. }
  41.  
  42. void graphShow(Grafo* G)
  43. {
  44.     int i, j;
  45.     for (i = 0; i < G->n; i++)
  46.     {
  47.         printf("%2d:", i);
  48.         for (j = 0; j < G->n; j++){
  49.             if (G->A[i][j] == 1){
  50.                 printf(" %2d", j);
  51.             }
  52.         }      
  53.         printf("\n");
  54.     }
  55. }
  56.  
  57.  
  58. int main() {
  59.     Grafo* gr = graphInit(5);
  60.     graphInsertArc(gr,0,1);
  61.     graphInsertArc(gr,1,2);
  62.     graphInsertArc(gr,2,4);
  63.     graphInsertArc(gr,3,1);
  64.     graphInsertArc(gr,4,3);
  65.     graphShow(gr);
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement