-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question 2 BellmanFord.cpp
129 lines (108 loc) · 2.54 KB
/
Question 2 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include<iostream>
using namespace std;
class Bellman
{
int *dis;
int *pi;
int capacity;
public:
Bellman(int);
void initialize(int);
void bFord(int **);
};
Bellman::Bellman(int cap) //PARAMETERISED CONSTRUCTOR USED FOR INITIALIZATION
{
capacity = cap;
dis = new int[capacity];
pi = new int[capacity];
}
void Bellman::initialize(int s) //INITIALIZING SOURCE VERTEX
{
for(int i=0; i<capacity; i++)
{
dis[i]=9999;
pi[i]=0;
}
dis[s]=0;
}
void Bellman::bFord(int **adj)
{
int u, j, flag=0;
for(int k=0; k<capacity; k++)
{
for(int i=0; i<capacity; i++)
{
for(int j=0; j<capacity; j++)
{
if(adj[i][j]!=0)
{
if(dis[j] > dis[i]+adj[i][j]) //CHECK CONDITION TO STORE APPROPRIATE VALUES IN THE TABLE
{
dis[j] = dis[i]+adj[i][j];
pi[j] = i;
}
}
}
}
}
for(int i=0; i<capacity; i++)
{
for(int j=0; j<capacity; j++)
{
if(adj[i][j]!=0)
{
if(dis[j] > dis[i]+adj[i][j])
{
flag=1;
cout<<"\nSORRY,,,,INVALID INPUT"; //INVALID INPUT
}
}
}
}
if(flag==0)
{
cout<<"\nFIANLISED RESULT IS ";
for(int i=0; i<capacity; i++)
cout<<"\nVertex "<<i+1<<", distance: "<<dis[i];
}
}
int main()
{
int v, e, src, dest, cost, strt;
cout<<"NO. OF VERTICES IN GRAPH";
cin>>v;
int **adj = new int*[v];
for(int i=0; i<v; i++)
adj[i]= new int[v];
for(int i=0; i<v; i++)
{
for(int j=0; j<v; j++)
adj[i][j]=0;
}
cout<<"\nNO. OF EDGES IN GRAPH ";
cin>>e;
cout<<"\nDETAILS FOR EACH EDGE\n";
for(int i=0; i<e; i++)
{
cout<<"\nSource Vertex: ";
cin>>src;
cout<<"Destination Vertex: ";
cin>>dest;
cout<<"Cost: ";
cin>>cost;
adj[src-1][dest-1]=cost;
}
cout<<"\nAdjacency Matrix\n";
for(int i=0; i<v; i++)
{
for(int j=0; j<v; j++)
cout<<adj[i][j]<<" ";
cout<<endl;
}
cout<<"\nEnter starting vertex: ";
cin>>strt;
Bellman b(v);
b.initialize(strt-1);
b.bFord(adj);
return 0;
}