가족 관계가 그래프 형태로 주어지고, 그래프를 따라 탐색하며 촌수를 1씩 더해가는 프로그램을 작성하면 된다.
모든 가족 관계를 둘러봤을 때, 서로 이어져있지 않다면 -1 출력!
from collections import deque
def main():
n = int(input()) # 전체 사람 수
x, y = map(int, input().split())
m = int(input()) # 간선 수
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
check = [0] * (n+1)
bfs(graph, x, check)
print(check[y] if check[y] > 0 else -1)
def bfs(graph, start, check):
queue = deque([start])
while queue:
v = queue.popleft()
for i in graph[v]:
if check[i] == 0:
queue.append(i)
check[i] = check[v] + 1
main()