-
Notifications
You must be signed in to change notification settings - Fork 36
/
chapter9-unweighted-shortest-path.cpp
88 lines (74 loc) · 1.42 KB
/
chapter9-unweighted-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
87
88
// A simple illustration for unweighted shortest path. Graph represented by adjacency matrix.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
void unweightedShortestPath(const vector<vector<bool> > &graph,
vector<int> &dist, vector<bool> &reachable)
{
// The minimal distances from 0th vertex to others.
int n;
int i, j;
n = (int)graph.size();
dist.resize(n);
reachable.resize(n);
if (n < 1) {
return;
}
for (i = 0; i < n; ++i) {
reachable[i] = false;
}
queue<int> q;
dist[0] = 0;
reachable[0] = true;
q.push(0);
while (!q.empty()) {
i = q.front();
q.pop();
for (j = 0; j < n; ++j) {
if (!graph[i][j] || reachable[j]) {
continue;
}
dist[j] = dist[i] + 1;
reachable[j] = true;
q.push(j);
}
}
}
int main()
{
vector<vector<bool> > graph;
vector<int> dist;
vector<bool> reachable;
int n;
int nk;
int i, j;
int tmp;
while (cin >> n && n > 0) {
graph.resize(n);
for (i = 0; i < n; ++i) {
graph[i].resize(n, false);
}
for (i = 0; i < n; ++i) {
cin >> nk;
for (j = 0; j < nk; ++j) {
cin >> tmp;
graph[i][tmp] = true;
}
}
unweightedShortestPath(graph, dist, reachable);
for (i = 0; i < n; ++i) {
cout << i << ": ";
if (reachable[i]) {
cout << dist[i] << endl;
} else {
cout << "Unreachable" << endl;
}
}
for (i = 0; i < n; ++i) {
graph[i].clear();
}
graph.clear();
}
return 0;
}