美文网首页
Concerning Graph Part III: Singl

Concerning Graph Part III: Singl

作者: 刘煌旭 | 来源:发表于2021-01-07 02:23 被阅读0次

We address single source paths problem here, using a depth first search solution.

#include "graph.c"
#include "linked_list_stack.c"
typedef struct DepthFirstPathStruct {
    bool *marked;
    int *edgeTo;
    int s;
}* DepthFirstPath;

void DepthFirstPathSearch(DepthFirstPath dfsp, Graph g, int v) {
    dfsp->marked[v] = true;
    int n = 0;
    int *adj = GraphAdjcency(g, v, &n);
    for (int i = 0; i < n; i++) { 
        if (!dfsp->marked[adj[i]]) { 
            dfsp->edgeTo[adj[i]] = v;
            DepthFirstPathSearch(dfsp, g, adj[i]); 
        } 
    }
    if (adj != NULL) free(adj);
}

bool DepthFirstPathHashPathTo(DepthFirstPath dfsp, int v) { return dfsp != NULL && dfsp->marked[v]; }

DepthFirstPath DepthFirstPathCreate(Graph g, int s) {
    DepthFirstPath dfsp = (DepthFirstPath)malloc(sizeof(*dfsp));
    dfsp->s = s;
    dfsp->marked = (bool*)malloc(sizeof(bool) * g->v);
    dfsp->edgeTo = (int*)malloc(sizeof(int) * g->v);
    DepthFirstPathSearch(dfsp, g, s);
    printa(dfsp->edgeTo, g->v);
    return dfsp;
}

void DepthFirstPathRelease(DepthFirstPath dfsp) {
    if (dfsp != NULL) {
        free(dfsp->edgeTo);
        free(dfsp->marked);
        free(dfsp);
    }
}

int* DepthFirstPathPathTo(DepthFirstPath dfsp, int v, int *n) {
    if (!DepthFirstPathHashPathTo(dfsp, v)) return NULL;
    LinkedListStack stack = LinkedListStackCreate();
    for (int i = v; i != dfsp->s; i = dfsp->edgeTo[i]) { LinkedListStackPush(stack, i); }
    LinkedListStackPush(stack, dfsp->s);
    int *paths = LinkedListStackItems(stack, n);
    free(stack);
    return paths;
}

相关文章

网友评论

      本文标题:Concerning Graph Part III: Singl

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