forked from algorithm-visualizer/tracers.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.cpp
More file actions
91 lines (81 loc) · 2.65 KB
/
test.cpp
File metadata and controls
91 lines (81 loc) · 2.65 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
// import visualization libraries {
#include "algorithm-visualizer.h"
// }
#include <vector>
#include <string>
#include <limits>
using namespace std;
int main() {
// define tracer variables
GraphTracer tracer = GraphTracer("Graph").weighted();
LogTracer logger = LogTracer("Console");
Layout::setRoot(VerticalLayout({tracer, logger}));
tracer.log(logger);
// create random weighted graph
const int N = 5;
const double ratio = 1.0; // fully connected
Randomize::Graph<int> rg(N, ratio);
rg.weighted(true);
vector<int> G(N * N);
rg.fill(G.data());
// convert adjacency matrix to json and set tracer
nlohmann::json jG = nlohmann::json::array();
for (int i = 0; i < N; i++) {
nlohmann::json row = nlohmann::json::array();
for (int j = 0; j < N; j++) {
row.push_back(G[i * N + j]);
}
jG.push_back(row);
}
tracer.set(jG);
Tracer::delay();
// Floyd--Warshall
const double MAX_VALUE = numeric_limits<double>::infinity();
vector<vector<double>> S(N, vector<double>(N));
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) S[i][j] = 0;
else if (G[i * N + j] > 0) S[i][j] = G[i * N + j];
else S[i][j] = MAX_VALUE;
}
}
logger.println("finding the shortest paths from and to all nodes");
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
if (k == i) continue;
// visualize
tracer.visit(k, i);
Tracer::delay();
for (int j = 0; j < N; j++) {
if (i == j || j == k) continue;
// visualize
tracer.visit(j, k);
Tracer::delay();
if (S[i][j] > S[i][k] + S[k][j]) {
// visualize
tracer.visit(j, i, S[i][j]);
Tracer::delay();
S[i][j] = S[i][k] + S[k][j];
// visualize
tracer.leave(j, i, S[i][j]);
}
// visualize
tracer.leave(j, k);
}
// visualize
tracer.leave(k, i);
Tracer::delay();
}
}
// logger output
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (S[i][j] == MAX_VALUE) {
logger.println(string("there is no path from ") + to_string(i) + " to " + to_string(j));
} else {
logger.println(string("the shortest path from ") + to_string(i) + " to " + to_string(j) + " is " + to_string(S[i][j]));
}
}
}
return 0;
}