본문 바로가기

Algorithm

C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 2644번:촌수계산 답

반응형

최단거리를 구하는 문제입니다. BFS를 이용하여 풀었습니다

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 <iostream>
#include <queue>
#include <vector>
using namespace std;
 
vector <int> family[101];
queue <int> q;
int n, m, a, b;
bool c[101];
int d[101];
 
int BFS(int x)
{
    q.push(x);
    c[x] = 1;
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        for (int i = 0; i < family[x].size(); i++)
        {
            int y = family[x][i];
            if (c[y] == 0)
            {
                q.push(y);
                c[y] = 1;
                d[y] = d[x] + 1;
                if (y == b)
                    return d[y];
            }
        }
    }
    return -1;
}
int main() {
 
    cin >> n;
    cin >> a >> b;
    cin >> m;
    while (m--)
    {
        int x, y;
        cin >> x >> y;
        family[x].push_back(y);
        family[y].push_back(x);
    }
    cout << BFS(a) << '\n';
}
cs