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;
}
'π Self Study > π BaekJoon' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
λ°±μ€ BaekJoon (μ€ννΈλ§ν¬, 5014λ²) C++ (0) | 2022.01.11 |
---|---|
λ°±μ€ BaekJoon (μ¨λ°κΌμ§, 1697λ²) C++ (0) | 2022.01.11 |
λ°±μ€ BaekJoon (ν λ§ν , 7569λ²) C++ (0) | 2022.01.11 |
λ°±μ€ BaekJoon (DFSμ BFS, 1260) C++ (0) | 2022.01.05 |
λ°±μ€ BaekJoon (λ°μ΄λ¬μ€, 2606) C++ (0) | 2022.01.05 |