Advertisement
IcaroPeretti

Untitled

Nov 30th, 2020
1,563
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include<stdio.h>
  2. #include <stdlib.h>
  3. #define true 1;
  4. #define false 0;
  5.  
  6. typedef struct adjacencia{
  7.     int vertice;
  8.     int peso;
  9.     struct adjacencia *next;
  10. }ADJACENCIA;
  11.  
  12. typedef struct vertice{
  13.     //Dados são armazenados aqui
  14.     ADJACENCIA *head;
  15. }VERTICE;
  16.  
  17. typedef struct grafo{
  18.     int vertices;
  19.     int arestas;
  20.     VERTICE *adj;
  21. }GRAFO;
  22.  
  23. GRAFO *criaGrafo(int v){
  24.     GRAFO *g = (GRAFO*)malloc(sizeof(GRAFO));
  25.     g->vertices = v;
  26.     g->arestas = 0;
  27.     g->adj = (VERTICE*)malloc(v*sizeof(VERTICE));
  28.     int i;
  29.     for(i= 0;i < v; i++){
  30.         g->adj[i].head = NULL;
  31.     }
  32.     return g;
  33. }
  34.  
  35. ADJACENCIA *criaAdj(int v,int peso){
  36.     ADJACENCIA *adj = (ADJACENCIA*)malloc(sizeof(ADJACENCIA));
  37.     adj->vertice = v;
  38.     adj->peso = peso;
  39.     adj->next = NULL;
  40.     return adj;
  41. }
  42.  
  43. int criaAresta(GRAFO* gr, int vi, int vf,int peso){
  44.     if(vf < 0 || vf >= gr->vertices){
  45.         return false;
  46.     }
  47.     if(vi < 0 || vi >= gr->vertices){
  48.         return false;
  49.     }
  50.     ADJACENCIA *nova = criaAdj(vf,peso);
  51.     nova->next = gr->adj[vi].head;
  52.     gr->adj[vi].head = nova;
  53.     gr->arestas++;
  54.     return true;
  55. }
  56.  
  57. void imprimir(GRAFO *gr){
  58.     if(gr != NULL){
  59.         printf("Vertices: %d. Arestas: %d.\n",gr->vertices,gr->arestas);
  60.         int i;
  61.         for(i = 0; i < gr->vertices; i++){
  62.             printf("V%d -> ",i);
  63.             ADJACENCIA *adj = gr->adj[i].head;
  64.             while(adj){
  65.                 printf("V%d(peso %d) ->",adj->vertice,adj->peso);
  66.                 adj = adj->next;
  67.             }
  68.             printf("\n");
  69.         }
  70.     }
  71.     return false;
  72. }
  73.  
  74. int main(){
  75.     GRAFO *gr = criaGrafo(5);
  76.  
  77.     criaAresta(gr,0,1,2);
  78.     criaAresta(gr,1,2,4);
  79.     criaAresta(gr,2,4,6);
  80.     criaAresta(gr,3,1,8);
  81.     criaAresta(gr,4,3,9);
  82.     criaAresta(gr,4,2,10);
  83.     imprimir(gr);
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement