-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bellmanford.cpp
76 lines (64 loc) · 1.95 KB
/
Bellmanford.cpp
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
#include <iostream>
using namespace std;
const int vertices = 5;
void bellmanford(int adjacency_matrix[vertices][vertices], int source)
{
int distance[vertices];
int predecessor[vertices];
for (int i = 0; i < vertices; i++)
{
distance[i] = 9999;
predecessor[i] = -1;
}
distance[source] = 0;
for (int i = 0; i < vertices; i++)
{
for (int j = 0; j < vertices; j++)
{
for (int k = 0; k < vertices; k++)
{
if (adjacency_matrix[j][k] != 0 && distance[j] + adjacency_matrix[j][k] < distance[k])
{
distance[k] = distance[j] + adjacency_matrix[j][k];
predecessor[k] = j;
}
}
}
}
for (int i = 0; i < vertices; i++)
{
for (int j = 1; j < vertices; j++)
{
if (adjacency_matrix[i][j] != 0 && distance[i] + adjacency_matrix[i][j] < distance[j])
{
cout << "The Graph contains negative weight cycle";
return;
}
}
}
cout << "Distance of all the vertices from source " << source << endl;
cout << "Vertex\tDistance\tpredecessor\n";
for (int i = 0; i < vertices; i++)
cout << i << "\t" << distance[i] << "\t\t" << predecessor[i] << endl;
}
int main()
{
int adjacency_matrix[vertices][vertices] = {
{0, 0, 6, 3, 0},
{3, 0, 0, 0, 0},
{0, 0, 0, 2, 0},
{0, 1, 1, 0, 0},
{0, 4, 0, 2, 0}
};
bellmanford(adjacency_matrix, 4);
return 0;
}
/* output
* Distance of all the vertices from source 4
* Vertex Distance predecessor
* 0 6 1
* 1 3 3
* 2 3 3
* 3 2 4
* 4 0 -1
*/