I have a homework to implement Bellman Ford's algorithm and test it on some graphs. I implemented the algorithm, tested it on 2 of 3 graphs and it works. But on the third graph I have no output when calling the function.
Graph* temaTrecuta = createGraph(10, 12);
addOrientedEdge(temaTrecuta, 0, 0, 1, 5);
addOrientedEdge(temaTrecuta, 1, 1, 2, 3);
addOrientedEdge(temaTrecuta, 2, 2, 3, 5);
addOrientedEdge(temaTrecuta, 4, 3, 9, 5);
addOrientedEdge(temaTrecuta, 5, 1, 9, 1);
addOrientedEdge(temaTrecuta, 6, 3, 4, 1);
addOrientedEdge(temaTrecuta, 7, 4, 8, 5);
addOrientedEdge(temaTrecuta, 8, 8, 7, 1);
addOrientedEdge(temaTrecuta, 9, 7, 5, 1);
addOrientedEdge(temaTrecuta, 10, 7, 6, 3);
addOrientedEdge(temaTrecuta, 11, 6, 0, 1);
This part creates the graph and its edges. The createGraph function takes as parameters number of vertices and edges.
void addOrientedEdge(Graph* graph, int index, int source, int destination, int cost) {
graph->edge[index].src = source;
graph->edge[index].dest = destination;
graph->edge[index].cost = cost;
graph->matrix[source][destination] = cost;
}
This is the function that adds a new edge.
Below is my implementation for Bellman Ford's algorithm.
void bellmanFord(Graph* gr, int src) {
int* dist = (int*)malloc(sizeof(int) * gr->V);
int* path = (int*)malloc(sizeof(int) * gr->V);
if (!path || !dist) {
printf("Nu am putut aloca.\n");
exit(1);
}
for (int i = 0; i < gr->V; ++i) {
dist[i] = INT_MAX;
path[i] = 0;
}
path[src] = -1;
dist[src] = 0;
for (int i = 1; i <= gr->V - 1; ++i) {
for (int j = 0; j < gr->E; ++j) {
int m = gr->edge[j].src;
int n = gr->edge[j].dest;
int cost = gr->edge[j].cost;
if (dist[m] != INT_MAX && dist[m] + cost < dist[n]) {
dist[n] = dist[m] + cost;
path[n] = m;
}
}
}
for (int i = 0; i < gr->E; ++i) {
int m = gr->edge[i].src;
int n = gr->edge[i].dest;
int cost = gr->edge[i].cost;
if (dist[m] != INT_MAX && dist[m] + cost < dist[n]) {
printf("Exista un ciclu negativ.");
return;
}
}
printBellmanSol(dist, gr->V, path);
free(dist);
free(path);
}