λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸš“ Self Study/πŸ”“ BaekJoon

λ°±μ€€ BaekJoon(촌수 계산, 2644번) C++

by UKHYUN22 2022. 1. 10.
728x90

 

촌수 계산을 Node κ°„μ˜ 거리둜 μ•Œκ³ λ¦¬μ¦˜μ„ κ΅¬μ„±ν–ˆλŠ”λ° μ™œ 성곡인지...? μ•„ 방금 촌수 κ³„μ‚°ν•˜λŠ” 법을 κ΅¬κΈ€λ§ν•˜κ³  μ™”λŠ”λ° 이게 λ§žλ‹€. γ…‹γ…‹γ…‹γ…‹γ…‹γ…‹γ…‹γ…‹γ…‹ 각 Nodeμ—μ„œ μ–Όλ§ˆλ‚˜ λ–¨μ–΄μ Έ μžˆλŠ”μ§€λ₯Ό κ³„μ‚°ν•˜λ©΄ 촌수λ₯Ό ꡬ할 수 μžˆλ‹€.

 

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int size = 0 ,me = 0, you = 0, num = 0;
    cin >> size;
    cin >> me >> you;
    cin >> num;

    vector<vector<int>> arr(size+1);
    vector<int> visited(size+1, 0);

    for(int i = 0 ; i < num ; i++) {
        int one = 0, two = 0;
        cin >> one >> two;
        arr[one].push_back(two);
        arr[two].push_back(one);
    }

    queue<int> q;

    q.push(me);
    visited[me] = 1;

    while(!q.empty()) {
        int node = q.front();
        q.pop();

        for(int j = 0 ; j < arr[node].size() ; j++) {
            if(visited[arr[node][j]] == 0) {
                visited[arr[node][j]] = visited[node] + 1;
                q.push(arr[node][j]);
            }
        }
    }
    // for(int i = 1 ; i <= num ; i++) {
    //     cout << "[" << i << "] ";
    //     for(int j = 0 ; j < arr[i].size() ; j++) {
    //         cout << arr[i][j] << " ";
    //     }
    //     cout << endl;
    // }

    if(visited[you] == 0)
        cout << "-1";
    else
        cout << visited[you] - 1;

    return 0;
}