美文网首页
Concerning Graph Part VII Digrap

Concerning Graph Part VII Digrap

作者: 刘煌旭 | 来源:发表于2021-01-15 00:47 被阅读0次

    We give the impl of digraph in this post:

    #include "linked_list_bag.c"
    #include "out.c"
    #ifndef DIGRAPH
    #define DIGRAPH
    typedef struct DigraphStruct {
        int v;
        int e;
        LinkedListBag *adj;
    }*Digraph;
    
    Digraph DigraphCreateV(int v) {
        Digraph dg = (Digraph)malloc(sizeof(*dg));
        dg->v = v;
        dg->e = 0;
        dg->adj = (LinkedListBag*)malloc(v * sizeof(LinkedListBag));
        for (int i = 0; i < v; i++) { *(dg->adj + i) = LinkedListBagCreate(); }
        return dg;
    }
    
    void DigraphAddEdge(Digraph dg, int v, int w) {
        if (dg == NULL) return;
        LinkedListBagAdd(dg->adj[v], w);
        dg->e++;
    }
    
    Digraph DigraphCreate(int v, int e, int a[]) {
        Digraph dg = DigraphCreateV(v);
        for (int i = 0; i < e; i++) { DigraphAddEdge(dg, *(a + 2 * i), *(a + 2 * i + 1)); }
        return dg;
    }
    
    /**
     * examle:
     * 3 //number of vetices
     * 3 //number of edges
     * 1 0
     * 1 2
     * 2 1
    */
    Digraph DigraphCreateFromInput() {
        int v, e, *a;
        scanf("%i%i", &v, &e);
        a = (int*)malloc(2 * e * sizeof(*a));
        for (int i = 0; i < e; i++) { scanf("%i%i", a + 2 * i, a + 2 * i + 1); }
        Digraph dg = DigraphCreate(v, e, a);
        free(a);
        return dg;
    }
    
    int* DigraphAdj(Digraph dg, int v, int *n) { return dg == NULL ? NULL : LinkedListBagItems(dg->adj[v], n); }
    
    Digraph DigraphReverse(Digraph dg) {
        if (dg == NULL) return NULL;
        Digraph rdg = DigraphCreateV(dg->v);
        for (int v = 0; v < dg->v; v++) {
            int n = 0;
            int *adj = DigraphAdj(dg, v, &n);
            for (int w = 0; w < n; w++) { DigraphAddEdge(rdg, w, v); }
        }
        return rdg;
    }
    
    void DigraphRelease(Digraph dg) { 
        if (dg != NULL) {
            for (int i = 0; i < dg->v; i++) { LinkedListBagRelease(dg->adj[i]); }
            free(dg); 
        }
    }
    
    void DigraphPrint(Digraph dg) {
        if (dg != NULL) {
            printf("%i vertices, %i edges\n", dg->v, dg->e);
            for (int i = 0; i < dg->v; i++) {
                printf("%i: ", i);
                int n = 0;
                int *adj = LinkedListBagItems(dg->adj[i], &n);
                if (adj != NULL) {
                    printa(adj, n);
                    free(adj);
                } else {
                    printf("\n");
                }
            }
            printf("\n");
        }
    }
    #endif
    

    相关文章

      网友评论

          本文标题:Concerning Graph Part VII Digrap

          本文链接:https://www.haomeiwen.com/subject/vwciaktx.html