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)
'BOJ 알고리즘 (T아카데미)' 카테고리의 다른 글
2667번: 단지번호 붙이기 (그래프, BFS) (0) | 2020.10.01 |
---|---|
13116번: 30번 (그래프, 부모배열) (0) | 2020.10.01 |
11866번: 요세푸스 문제 0 (구현, 큐) - Tacademy (0) | 2020.10.01 |
9012번: 괄호 (구현, 스택) - Tacademy (0) | 2020.10.01 |
11729번: 하노이탑 (구현, 재귀) - Tacademy (0) | 2020.10.01 |