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
|
#include<iostream>
#include<stdio.h>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
typedef vector<vector<int>> graph;
void print(graph g)
{
for (int i = 0; i < int(g.size()); ++i)
{
cout << i + 1 << ": ";
for (int j = 0; j < int(g[i].size()) - 1; ++j)
cout << g[i][j] + 1 << ", ";
if (g[i].size() > 0)
cout << g[i].back() + 1;
else
cout << "нет смежных вершин";
cout << ";" << endl;
}
}
void bfs( int a,
int b,
graph g,
vector<int> *paths,
vector<int> *used,
queue<int> *q )
{
(*used)[a] = 1;
q->push(a);
while (q->size() > 0)
{
int y = q->front();
q->pop();
for (int i = 0; i < int(g[y].size()); ++i)
{
int node = g[y][i];
if ((*used)[node] == 0)
{
(*used)[node] = 1;
if ((*paths)[node] == -1)
(*paths)[node] = y;
q->push(node);
if(node == b) return;
}
}
}
}
void bfs(int a, int b, graph g, vector<int> *path)
{
int n = int(g.size());
vector<int> used(n, 0);
queue<int> q;
vector<int> paths(n, -1);
bfs(a, b, g, &paths, &used, &q);
int cur = b;
while (true)
{
path->push_back(cur);
if (cur == a) break;
if (cur == -1)
{
path->clear();
break;
}
cur = paths[cur];
}
reverse(path->begin(), path->end());
}
int main()
{
cout << "Введите количество вершин: ";
int n;
cin >> n;
cout << "Введите количество рёбер: ";
int k;
cin >> k;
graph g(n);
cout << "o----------------------o" << endl;
cout << "| Нумерация вершин с 1 |" << endl;
cout << "o----------------------o" << endl;
cout << "Введите рёбра (неориентированные):" << endl;
for (int i = 0; i < k; ++i)
{
int a, b;
cin >> a >> b;
a--;
b--;
g[a].push_back(b);
g[b].push_back(a);
}
cout << "Введённый граф:" << endl;
print(g);
cout << "Введите вершины, между которыми нужно найти путь:" << endl;
int a, b;
cin >> a >> b;
a--;
b--;
vector<int> path;
bfs(a, b, g, &path);
if (path.size() > 0)
{
printf("Найден путь из вершины %i в вершину %i:\n", a + 1, b + 1);
for (int i = 0; i < int(path.size()) - 1; ++i)
cout << path[i] + 1 << " -> ";
cout << path.back() + 1 << endl;
}
else
printf("Путь из вершины %i в вершину %i не найден.\n", a + 1, b + 1);
return 0;
}
|