#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int peoplenum, firstpeople, secondpeople, linknum;
vector<pair<int, int>> v;
int countans[100];
int num,maxnum=987654321;
void bfs(void) {
queue<int> q;
q.push(firstpeople);
while (!q.empty()) {
int people = q.front();
q.pop();
if (people == secondpeople) {
cout << countans[secondpeople];
return;
}
for (int i = 0; i < v.size(); i++) {
if (v[i].first == people) {
if (countans[v[i].second] == 0) {
q.push(v[i].second);
countans[v[i].second] = countans[people] + 1;
}
}
}
}
cout << "-1";
return;
}
int main(void) {
cin >> peoplenum;
cin >> firstpeople >> secondpeople;
cin >> linknum;
memset(countans, 0, sizeof(countans));
for (int i = 0; i < linknum; i++) {
int parent, child;
cin >> parent >> child;
v.push_back(make_pair(parent, child));
v.push_back(make_pair(child, parent));
}
bfs();
}
'백준 알고리즘 > BFS' 카테고리의 다른 글
백준 10026번 C++ (0) | 2019.01.13 |
---|---|
백준 1389번 C++ (0) | 2019.01.13 |
백준 14502번 C++ (0) | 2019.01.10 |
백준 2468번 C++ (0) | 2019.01.09 |
백준 11724번 C++ (0) | 2019.01.09 |