美文网首页
Concerning Graph Part VIII Cycle

Concerning Graph Part VIII Cycle

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

We give the impl of a digraph cycle detection in this post:

#include "digraph.c"
#include "linked_list_stack.c"
#ifndef DIRECTED_CYCLE
#define DIRECTED_CYCLE
typedef struct DirectedCycleStruct {
    LinkedListStack cycle;
    bool cyclic;
}*DirectedCycle;

void DirectedCycleDFSearch(DirectedCycle dc, Digraph dg, int v, bool *marked, int *edgeTo, bool *onStack) {
    onStack[v] = true;
    marked[v] = true;
    int n = 0;
    int *adj = DigraphAdj(dg, v, &n);
    for (int i = 0; i < n; i++) {
        int w = adj[i];
        if (dc->cyclic) {
            return;
        }  else if (!marked[w]) {
            edgeTo[w] = v;
            DirectedCycleDFSearch(dc, dg, w, marked, edgeTo, onStack);
        } else if (onStack[w]) {
            dc->cyclic = true;
            dc->cycle = LinkedListStackCreate();
            for (int x = v; x != w; x = edgeTo[x]) { LinkedListStackPush(dc->cycle, x); }
            LinkedListStackPush(dc->cycle, w);
            LinkedListStackPush(dc->cycle, v);
        }
    }
    onStack[v] = false;
}

DirectedCycle DirectedCycleCreate(Digraph dg) {
    DirectedCycle dc = (DirectedCycle)malloc(sizeof(*dc));
    dc->cyclic = false;
    dc->cycle = NULL;
    bool *marked = (bool*)malloc(dg->v * sizeof(bool));
    int *edgeTo = (int*)malloc(dg->v * sizeof(int));
    bool *onStack = (bool*)malloc(dg->v * sizeof(bool));
    for (int v = 0; v < dg->v; v++) { if (!marked[v]) DirectedCycleDFSearch(dc, dg, v, marked, edgeTo, onStack); }
    free(marked);
    free(edgeTo);
    free(onStack);
    return dc;
}

void DirectedCycleRelease(DirectedCycle dc) {
    if (dc == NULL) return;
    if (dc->cycle == NULL) free(dc->cycle);
    free(dc);
}

bool DirectedCycleCyclic(DirectedCycle dc) { return dc != NULL && dc->cyclic; }

int* DirectedCycleCycle(DirectedCycle dc, int *n) { return DirectedCycleCyclic(dc) ? LinkedListStackItems(dc->cycle, n) : NULL; }
#endif

相关文章

网友评论

      本文标题:Concerning Graph Part VIII Cycle

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