This repository has been archived by the owner on Oct 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bellmanford.h
138 lines (122 loc) · 2.33 KB
/
bellmanford.h
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
130
131
132
133
134
135
136
137
138
#ifndef bellmanford_h
#define bellmanford_h
#include <iostream>
#include <vector>
using namespace std;
#define max 99
class Node
{
public:
string label;
bool visited;
int cost;
string pred;
Node()
{
}
Node(string s)
{
label = s;
visited = false;
cost = max;
}
Node(string s, int cst)
{
label = s;
visited = false;
cost = cst;
}
};
class Graph
{
public:
vector< vector<Node> > graph;
int n;
Graph()
{
string s;
cout <<" Enter Number Of Vertices : ";
cin >>n;
string t;
for (int i = 0; i < n; i++)
{
vector<Node> singleList;
cout<<"\n Details For Vertex "<<i + 1 <<"\n";
cout <<"\n Enter Label Of Node : ";
cin >>s;
singleList.push_back(Node(s, 0));
cout <<"\n Enter Number of Adjacent Nodes : ";
int n2, cst;
cin >>n2;
for (int j = 0; j < n2; j++)
{
cout<<"\n Details For Adjacent Node "<<j + 1<<"\n";
cout <<"\n Enter Label Of Adjacent Node : ";
cin>>s;
cout<<"\n Enter Cost : ";
cin>>cst;
singleList.push_back(Node(s, cst));
}
graph.push_back(singleList);
}
}
int display()
{
cout<<"\n\n Displaying Graph Details \n\n";
for (int i = 0; i < n; i++)
{
int s = graph[i].size();
for (int j = 0; j < s; j++)
{
cout <<" "<<graph[i][j].label<<" "<< graph[i][j].cost<<"\n";
}
}
cout<<"\n\n";
return 0;
}
int findNode(string l)
{
for (int i = 0; i < n; i++)
{
if (graph[i][0].label == l)return i;
}
return -1;
}
int bellmanford(string x)
{
int y = findNode(x);
for (int i=0; i<n; i++)
{
if (i==y)
{
graph[i][0].cost = 0;
}
else
{
graph[i][0].cost = max;
}
}
for(int k=0;k<n-1;k++)
{
for (int i=0; i<n; i++)
{
int s = graph[i].size();
for (int j=1; j<s; j++)
{
int c = findNode(graph[i][j].label);
if (graph[i][j].cost+graph[i][0].cost<graph[c][0].cost)
{
graph[c][0].cost = graph[i][j].cost+graph[i][0].cost;
graph[c][0].pred = graph[i][0].label;
}
}
}
}
for (int i=0; i<n; i++)
{
cout<<" "<<graph[i][0].label<<" - "<<graph[i][0].cost<<endl;
}
cout<<endl<<endl;
}
};
#endif