-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbellman-ford.cpp
98 lines (92 loc) · 1.88 KB
/
bellman-ford.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* @file bellman-ford.cpp
* @author prakash ([email protected])
* @brief Bellman-Ford shortest path algorithm in O(V^2) time.
* @version 0.1
* @date 2021-07-26
*
* @copyright Copyright (c) 2021
*
*/
#include <iostream>
#include <vector>
using namespace std;
/**
* @brief Vertex structure
*
*/
struct Vertex {
int id;
int distance;
int previous;
};
/**
* @brief Graph structure
*
*/
struct Graph {
int V;
vector<Vertex> graph;
};
/**
* @brief Bellman-Ford shortest path algorithm in O(V^2) time.
*
* @param graph - Graph object.
* @param source - Source vertex.
* @return - True if the algorithm is successful, false otherwise.
*/
bool bellman_ford(Graph graph, Vertex source) {
int V = graph.V;
int i, j;
bool flag = true;
Vertex temp;
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (graph.graph[j].distance >
graph.graph[j].distance + graph.graph[j].previous) {
flag = false;
break;
}
}
if (flag == false) {
break;
}
}
if (flag == true) {
return true;
} else {
return false;
}
}
int main(int argc, const char **argv) {
Graph graph;
Vertex source;
int V, i;
V = 5;
graph.V = V;
graph.graph.resize(V);
graph.graph[0].id = 0;
graph.graph[0].distance = 0;
graph.graph[0].previous = -1;
graph.graph[1].id = 1;
graph.graph[1].distance = 6;
graph.graph[1].previous = 0;
graph.graph[2].id = 2;
graph.graph[2].distance = 5;
graph.graph[2].previous = 1;
graph.graph[3].id = 3;
graph.graph[3].distance = 3;
graph.graph[3].previous = 2;
graph.graph[4].id = 4;
graph.graph[4].distance = 2;
graph.graph[4].previous = 3;
source.id = 0;
source.distance = 0;
source.previous = -1;
if (bellman_ford(graph, source)) {
cout << "Graph is an acyclic graph." << endl;
} else {
cout << "Graph is not an acyclic graph." << endl;
}
return 0;
}