Repository navigation
Expand file tree
/
Copy pathBellmanFord.cpp
More file actions
97 lines (78 loc) · 1.87 KB
/
Copy pathBellmanFord.cpp
File metadata and controls
97 lines (78 loc) · 1.87 KB
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
#include <bits/stdc++.h>
using namespace std;
class edge{
public:
int src;
int dest;
int weight;
};
edge* Edges=NULL;
int V,E;
int dist[100];
// shortest path from src to all the vertices inside a graph with no negative cycle.
// Edge Bucket
void BellmanFord(){
// shortest path cannot have more than V-1 edges.
for(int i=1;i<=V-1;i++){
for(int j=0;j<E;j++){
int u=Edges[j].src;
int v=Edges[j].dest;
int w=Edges[j].weight;
if(dist[u]!=INT_MAX && dist[v] > dist[u]+w){
dist[v]=dist[u]+w;
}
}
}
for(int j=0;j<E;j++){
int u=Edges[j].src;
int v=Edges[j].dest;
int w=Edges[j].weight;
if(dist[u]!=INT_MAX && dist[v] > dist[u]+w){
cout<<"Negative weight cycle exixts!\n";
return;
}
}
cout<<"vertex --- distance\n";
for(int i=0;i<V;i++){
cout<<i<<" "<<dist[i]<<"\n";
}
return;
}
void init(int src){
for(int i=0;i<=V;i++){dist[i]=INT_MAX;}
dist[src]=0;
return;
}
int main(){
V = 5; // Number of vertices in graph
E = 8; // Number of edges in graph
Edges=new edge[E];
Edges[0].src = 0;
Edges[0].dest = 1;
Edges[0].weight = -1;
Edges[1].src = 0;
Edges[1].dest = 2;
Edges[1].weight = 4;
Edges[2].src = 1;
Edges[2].dest = 2;
Edges[2].weight = 3;
Edges[3].src = 1;
Edges[3].dest = 3;
Edges[3].weight = 2;
Edges[4].src = 1;
Edges[4].dest = 4;
Edges[4].weight = 2;
Edges[5].src = 3;
Edges[5].dest = 2;
Edges[5].weight = 5;
Edges[6].src = 3;
Edges[6].dest = 1;
Edges[6].weight = 1;
Edges[7].src = 4;
Edges[7].dest = 3;
Edges[7].weight = -3;
int src=0;
init(src);
BellmanFord();
return 0;
}