forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implemented a Bellman Ford Algorithm
84 lines (67 loc) · 2.15 KB
/
Implemented a Bellman Ford Algorithm
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
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Structure to represent an edge in the graph
struct Edge {
int source, destination, weight;
};
// Class to represent a directed, weighted graph
class Graph {
public:
int vertices, edges;
vector<Edge> edgeList;
Graph(int v, int e) {
vertices = v;
edges = e;
edgeList.resize(e);
}
void addEdge(int source, int destination, int weight) {
edgeList.push_back({source, destination, weight});
}
void bellmanFord(int source) {
vector<int> distance(vertices, INT_MAX);
distance[source] = 0;
for (int i = 0; i < vertices - 1; ++i) {
for (const Edge& edge : edgeList) {
int u = edge.source;
int v = edge.destination;
int w = edge.weight;
if (distance[u] != INT_MAX && distance[u] + w < distance[v]) {
distance[v] = distance[u] + w;
}
}
}
// Check for negative-weight cycles
for (const Edge& edge : edgeList) {
int u = edge.source;
int v = edge.destination;
int w = edge.weight;
if (distance[u] != INT_MAX && distance[u] + w < distance[v]) {
cout << "Graph contains a negative-weight cycle!" << endl;
return;
}
}
// Print the shortest distances from the source vertex
cout << "Shortest distances from vertex " << source << ":" << endl;
for (int i = 0; i < vertices; ++i) {
cout << "Vertex " << i << ": Distance = " << distance[i] << endl;
}
}
};
int main() {
int v, e, source;
cout << "Enter the number of vertices and edges: ";
cin >> v >> e;
Graph graph(v, e);
cout << "Enter the edges (source, destination, weight):" << endl;
for (int i = 0; i < e; ++i) {
int source, destination, weight;
cin >> source >> destination >> weight;
graph.addEdge(source, destination, weight);
}
cout << "Enter the source vertex: ";
cin >> source;
graph.bellmanFord(source);
return 0;
}