#include <stdio.h>
#include <limits.h>
#define V 4
#define E 6
typedef struct Edge {
int src, dest, weight;
} Edge;
void bellmanFord(Edge edges[], int n, int src) {
int dist[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
dist[src] = 0;
for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < n; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int w = edges[j].weight;
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
}
// Check for negative weight cycles
for (int j = 0; j < n; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int w = edges[j].weight;
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
printf("Graph contains negative weight cycle\n");
return;
}
}
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%c\t%d\n", 'A' + i, dist[i]);
}
}
int main() {
Edge edges[E] = {
{0, 1, -1}, // A->B
{0, 2, 4}, // A->C
{1, 2, 3}, // B->C
{1, 3, 2}, // B->D
{3, 1, 1}, // D->B
{3, 2, -3} // D->C
};
bellmanFord(edges, E, 0); // Start from A (0)
return 0;
}
Initialize source distance to zero
for (int i = 1; i <= V - 1; i++) {
Repeat relaxation for all edges V-1 times
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
Relax edge if shorter path found
Update distance to destination node
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
Check for negative weight cycle after relaxation
printf("Graph contains negative weight cycle\n");
Report negative cycle if detected
Vertex Distance from Source
A 0
B -1
C -2
D 1