문제링크 : 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 함수에서 카운트를 같이 넘겨준다.
'백준 > 실버' 카테고리의 다른 글
[백준 2504번] 괄호의 값 (C++) (0) | 2023.02.06 |
---|---|
[백준 11725번] 트리의 부모 찾기 (C++) (0) | 2023.02.06 |
[백준 4963번] 섬의 개수 (C++) (0) | 2023.02.06 |
[백준 7562번] 나이트의 이동 (C++) (0) | 2023.02.06 |
[백준 11060번] 점프 점프 (C++) (0) | 2023.02.06 |