개발자 블로그
2664번 촌수계산 본문
2644번: 촌수계산
사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어
www.acmicpc.net
나의 풀이
from collections import deque, defaultdict
def relation_people(people, start_person, relation_graph):
q = deque()
q.append(start_person)
chon_list = [-1] * (people + 1)
chon_list[start_person] = 0
while q:
cur_person = q.popleft()
for person in relation_graph[cur_person]:
if chon_list[person] == -1:
chon_list[person] = chon_list[cur_person] + 1
q.append(person)
return chon_list
people = int(input())
start_person, target_person = map(int, input().split())
relations = int(input())
relation_graph = defaultdict(list)
for _ in range(relations):
parent, child = map(int, input().split())
relation_graph[parent].append(child)
relation_graph[child].append(parent)
answer = relation_people(people, start_person, relation_graph)
print(answer[target_person])
촌수 정보가 담긴 리스트를 만들고 각 인덱스가 시작하는 사람과의 촌수 정보가 담긴다. bfs함수를 시작 노드로 부터 인접 노드들을 돌떄마다 +1을 해주어 촌수 정보리스트를 업데이트!
*각 노드들의 관계를 그래프로 그려보고 문제를 풀어보자!
'알고리즘 > 백준' 카테고리의 다른 글
10451번 순열 사이클 (0) | 2022.07.29 |
---|---|
1525번 퍼즐 (0) | 2022.07.28 |
1697번 숨바꼭질 (0) | 2022.07.25 |
2468번 안전 영역 (0) | 2022.07.24 |
7576번 토마토 (0) | 2022.07.21 |