본문 바로가기

BOJ 알고리즘 (T아카데미)

2644번: 촌수계산 (그래프, BFS)

www.acmicpc.net/problem/2644

 

2644번: 촌수계산

사람들은 1, 2, 3, …, n (1≤n≤100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어진�

www.acmicpc.net

# 촌수계산
# https://www.acmicpc.net/problem/2644 (그래프, BFS)

from collections import deque


def bfs(graph, st, ed):
    visited = []
    queue = deque([(st, 0)])

    while queue:
        v, cnt = queue.popleft()
        if v in visited:
            continue

        visited.append(v)
        if v == ed:
            return cnt

        for e in graph[v]:
            if e not in visited:
                queue.append((e, cnt + 1))

    return -1


n = int(input())
st, ed = map(int, input().split())
graph = {i: [] for i in range(1, n + 1)}

r = int(input())
for _ in range(r):
    x, y = map(int, input().split())
    graph[x].append(y)
    graph[y].append(x)

cnt = bfs(graph, st, ed)
print(cnt)