-
Notifications
You must be signed in to change notification settings - Fork 0
/
grafos.cpp
48 lines (46 loc) · 1.08 KB
/
grafos.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
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<int> > adj(n + 1); // matriz de adjacencia.
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a); // se for bidirecional.
}
int c, b;
cin >> c >> b;
// busca em largura
queue<int> q;
q.push(c);
int pai[n + 1];
for (int i = 0; i <= n; i++) pai[i] = -1;
pai[c] = c;
while (!q.empty()) {
int no = q.front();
q.pop();
if (no == b) {
break;
}
for (int i = 0; i < adj[no].size(); i++) {
if (pai[adj[no][i]] == -1) {
q.push(adj[no][i]);
pai[adj[no][i]] = no;
}
}
}
vector<int> caminho;
int at = b;
while (at != c) {
caminho.push_back(at);
at = pai[at];
}
caminho.push_back(c);
reverse(caminho.begin(), caminho.end());
for (int i = 0; i < caminho.size(); i++) {
cout << caminho[i] << " ";
}
cout << endl;
}