2644번: 촌수계산
사람들은 1, 2, 3, …, n (1≤n≤100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어진�
www.acmicpc.net
bfs를 사용하는 문제. 그냥 찾는게 아니라, 깊이를 따져서 해당 숫자가 깊이 몇에 있는지 따져가며 탐색 해야한다. 그 부분만 주의하고 알고 있으면 풀 수 있다.
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
int n, x, y, t, a, b;
int depth[101];
void bfs(int start, vector <int> graph[], bool check[]){
depth[start] = 0;
bool stop = false;
queue<int> q;
q.push(start);
check[start] = true;
while(!q.empty()){
int temp = q.front();
q.pop();
for(int i=0; i<graph[temp].size(); i++){
if(graph[temp][i]==y)
stop = true;
if(check[graph[temp][i]]==false){
q.push(graph[temp][i]);
check[graph[temp][i]] = true;
depth[graph[temp][i]] = depth[temp] + 1;
}
}
}
if(!stop)
printf("-1");
else
printf("%d",depth[y]);
}
int main(void){
scanf("%d", &n);
vector<int> graph[n+1];
bool check[n+1];
fill(check, check+n+1, false);
scanf("%d %d", &x, &y);
scanf("%d", &t);
for(int i=0; i<t; i++){
scanf("%d %d", &a, &b);
graph[a].push_back(b);
graph[b].push_back(a);
}
bfs(x, graph, check);
}
'알고리즘 문제' 카테고리의 다른 글
[C/C++ 백준 11653번] 소인수분해 (Silver 4) (0) | 2020.09.29 |
---|---|
[C/C++ 백준 3184번] 양 (Silver 2) (0) | 2020.09.28 |
[C/C++ 백준 4963번] 섬의 개수 (Silver 2) (0) | 2020.09.24 |
[C/C++ 백준 1012번] 유기농 배추 (Silver 2) (0) | 2020.09.24 |
[C/C++ 백준 11724번] 연결 요소의 개수 (Silver 2) (0) | 2020.09.23 |