백준/실버
[백준 2644번] 촌수계산 (C++)
게임개발기원
2023. 2. 6. 01:28
문제링크 : https://www.acmicpc.net/problem/2644
#include <bits/stdc++.h>
using namespace std;
int n, m;
int n1, n2;
vector<int>v[101];
int x, y;
int result = 0;
bool check[101];
void dfs(int cur, int end, int cnt)
{
check[cur] = true;
if (cur == end) //해당 값 찾으면 카운트 저장
{
result = cnt;
}
for (int i = 0; i < v[cur].size(); i++)
{
if (!check[v[cur][i]]) //v[cur][i]는 다음 값을 가리킴
{
dfs(v[cur][i], end, cnt+1); //다음 값 부터 n2까지 탐색하며 카운트 증가
}
}
}
int main()
{
cin >> n; //총 사람 수
cin >> n1 >> n2; //촌수 계산해야 하는 두 사람
cin >> m; //부모 자식들 간의 관계의 개수
while (m--)
{
cin >> x >> y; //부모 자식간의 관계 (x = y의 부모 번호)
v[x].push_back(y);
v[y].push_back(x);
}
dfs(n1, n2, 0);
if (result != 0)
{
cout << result;
}
else
{
cout << -1;
}
}
dfs 함수에서 카운트를 같이 넘겨준다.