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;
}
网友评论