-
Notifications
You must be signed in to change notification settings - Fork 36
/
chapter9-all-pairs-shortest-path.cpp
86 lines (73 loc) · 1.46 KB
/
chapter9-all-pairs-shortest-path.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
// A simple illustration for all pairs shortest path using Floyd Algorithm.
#include <iostream>
#include <vector>
using namespace std;
const int INFINITY = 1000000000;
void floydAlgorithm(const vector<vector<int> > &graph,
vector<vector<int> > &dist)
{
int n;
int i, j, k;
n = (int)graph.size();
dist.resize(n);
for (i = 0; i < n; ++i) {
dist[i].resize(n, INFINITY);
}
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
dist[i][j] = graph[i][j];
}
}
for (k = 0; k < n; ++k) {
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
if (dist[i][k] + dist[k][j] >= dist[i][j]) {
continue;
}
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
int main()
{
vector<vector<int> > graph;
vector<vector<int> > dist;
int n;
int nk;
int i, j;
int tmp, tmp_dist;
while (cin >> n && n > 0) {
graph.resize(n);
for (i = 0; i < n; ++i) {
graph[i].resize(n, INFINITY);
}
for (i = 0; i < n; ++i) {
cin >> nk;
for (j = 0; j < nk; ++j) {
cin >> tmp >> tmp_dist;
graph[i][tmp] = tmp_dist;
}
}
floydAlgorithm(graph, dist);
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
cout << "[" << i << "][" << j << "]: ";
if (dist[i][j] < INFINITY) {
cout << dist[i][j] << endl;
} else {
cout << "Unreachable" << endl;
}
}
}
for (i = 0; i < n; ++i) {
graph[i].clear();
}
graph.clear();
for (i = 0; i < n; ++i) {
dist[i].clear();
}
dist.clear();
}
return 0;
}