-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathBellman Ford.cpp
94 lines (67 loc) · 1.43 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
// Bellman Ford's Algorithm for finding the shortest path in weighted graphs
#include <iostream>
#include <climits>
using namespace std;
class Edge{
public:
int src,dest,weight;
Edge(int src,int dest,int weight){
this->weight = weight;
this->src = src;
this->dest = dest;
}
Edge(){}
};
class Graph{
int v,e;
Edge* arr;
public:
Graph(int v,int e){
this->v = v;
this->e = e;
arr = new Edge[e];
}
void addEdge(int src,int dest,int weight,int node){
arr[node].src = src;
arr[node].dest = dest;
arr[node].weight = weight;
}
void bellmenFord(int src){
int distance[v];
for(int i=0;i<v;i++){
if(v==src){
distance[v] = 0;
}else{
distance[v] = INT_MAX;
}
}
for(int i=1;i<=v-1;i++){
for(int j = 0;j < e;j++){
int s = arr[j].src;
int d = arr[j].dest;
int wt = arr[j].weight;
if(distance[s]!=INT_MAX and distance[s] + wt < distance[d]){
distance[d] = distance[s] + wt;
cout<<"Update Check ";
cout<<s<<" "<<d<<" "<<wt<<" -> Result is ";
cout<<distance[d]<<endl;
}
}
}
for(int i=0;i<v;i++){
cout<<"Node "<<i<<" is at a distance of "<<distance[i]<<endl;
}
}
};
int main(){
int v,e;
cin>>v>>e;
Graph g(v,e);
for(int i=0;i<e;i++){
int src,dest,weight;
cin>>src>>dest>>weight;
g.addEdge(src,dest,weight,i);
}
g.bellmenFord(0);
return 0;
}