forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bellman_ford.c
111 lines (102 loc) · 2.01 KB
/
bellman_ford.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdio.h>
#include <math.h>
//Bellman Ford Function
int Bellman_Ford(int k, int *A, int *B, int n)
{
int i, j;
for (i = 0; i < n; i++)
{
*(B + (k + 1) * n + i) = *(B + k * n + i);
for (j = 0; j < n; j++)
{
if (*(B + (k + 1) * n + i) > *(B + k * n + j) + *(A + *(B + j) * n + *(B + i)))
*(B + (k + 1) * n + i) = *(B + k * n + j) + *(A + *(B + j) * n + *(B + i));
}
}
if (k < n)
Bellman_Ford(k + 1, A, B, n);
}
//Main Function Began
int main()
{
int n, i, j, k, a;
printf("Please enter the number of vertices:");
scanf("%d", &n);
int A[n][n], B[n + 2][n];
printf("\nEnter the value of Adjacency Matrix:\n");
for (i = 0; i < n; i++)
{
printf("\n");
for (j = 0; j < n; j++)
{
scanf("%d", &A[i][j]);
}
}
printf("\nEnter the Source vertex number:");
scanf("%d", &a);
/*Calculation for the first vertex*/
B[0][0] = a - 1;
B[1][0] = 0;
for (j = 1; j < n; j++)
{
if (j > a - 1)
B[0][j] = j;
else
B[0][j] = j - 1;
}
for (j = 1; j < n; j++)
B[1][j] = 99;
//calling bellman function
Bellman_Ford(1, A, B, n);
//check for negative cycle
for (i = 0; i < n; i++)
{
if (B[n + 1][i] != B[n][i])
{
printf("\n Negative edge-cycle Present");
return 0;
}
}
//print the output
printf("\n\tOUTPUT:\n");
for (i = 1; i < n; i++)
printf("\nWeight of vertex no.%d is %d", B[0][i] + 1, B[n + 1][i]);
}
//main ends here
/* Sample Input Output
Please enter the number of vertices: 5
Enter the value of Adjacency Matrix:
0
3
8
99
-4
99
0
99
1
7
99
4
0
99
99
2
99
5
0
99
99
99
99
6
0
Enter the Source vertex number: 1
OUTPUT:
Weight of vertex no.2 is 3
Weight of vertex no.3 is 7
Weight of vertex no.4 is 2
Weight of vertex no.5 is -4
Time Complexity : O(V*E)
where V is noumber of vertices and E is no. of edges in the graph.
*/