#include "pch.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
typedef struct node {
int key;
int color;
int d;
int f;
struct node* parent;
struct node* next;
} node;
typedef struct Graph {
int nr;
struct node** adj;
} Graph;
struct node* createNode(int v) {
struct node* newNode = (node*)malloc(sizeof(struct node));
newNode->key = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int n) {
struct Graph* graph = (Graph*)malloc(sizeof(struct Graph));
graph->nr = n;
graph->adj = (node**)malloc((n+1) * sizeof(struct node*));
int i;
for (i = 0; i < n; i++)
graph->adj[i] = NULL;
return graph;
}
void addEdge(struct Graph* graph, int s, int d) {
struct node* newNode = createNode(d);
newNode->next = graph->adj[s];
graph->adj[s] = newNode;
}
void printGraph(struct Graph* g) {
for (int i = 0; i < g->nr; i++) {
struct node* temp = g->adj[i];
printf("\n%d -> ", i);
while (temp) {
printf("%d -> ", temp->key);
temp = temp->next;
}
printf("\n");
}
}
// topological sort + disc. time + final time pt noduri
void DFS_VISIT_test(Graph* G, node* u, int* time, node** s) {
*time = *time + 1;
u->d = *time;
u->color = 1;
node* v = G->adj[u->key];
if (v) {
while (v) {
if (v->color == 0) {
v->parent = u;
DFS_VISIT_test(G, v, time,s);
}
v = v->next;
}
}
//trebuia functie push dar am facut fara pt moment
node* q = (node*)malloc(sizeof(node));
q->next = (*s);
q->key = u->key;
(*s) = q;
u->color = 2;
*time = *time + 1;
u->f = *time;
}
void DFStest(Graph* g) {
node* s = (node*)malloc(sizeof(node));
s->key = NULL;
s->next = NULL;
for (int i = 0; i < g->nr; i++) {
g->adj[i]->color = 0;
g->adj[i]->parent = NULL;
}
int time = 0;
node* u;
for (int i = 0; i < g->nr; i++) {
u = g->adj[i];
if (u->color == 0) {
DFS_VISIT_test(g, u, &time,&s);
}
}
//print stack
while (s) {
printf("%d", s->key);
s = s->next;
}
printf("\n");
//afisare discovery and final time
for (int i = 0; i < g->nr; i++) printf("%d - %d %d\n", i, g->adj[i]-\>d, g->adj[i]->f);
}
int main(){
Graph* g = createGraph(5);
/*
* pt topological sort, inca incerc
0
/ \
1 2
\ \
3 4
*/
addEdge(g, 0, 2);
addEdge(g, 0, 1);
addEdge(g, 1, 3);
addEdge(g, 2, 4);
printGraph(g);
DFStest(g);
return 0;
}
Through trial and error I discovered the problem but I am dumbfounded to the solution, I am sorry if it may be an obvious one but I tried it for 6 hours and I cannot wrap my head around it. Let's say I dynamically allocate the missing g->adj[i]
, then the if(v) while(v)
will have a problem because the nodes don't point to anything, how do I solve this?