Private 난이도 : ♥♥♡♡♡
2644번: 촌수계산
사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어
www.acmicpc.net
from collections import defaultdict
from sys import setrecursionlimit
setrecursionlimit(10**6)
n=int(input()) # 전체 사람 수
a,b =map(int,input().split(' ')) # 촌수를 구해야 하는 두 사람
m=int(input()) # 관계 수
graph=defaultdict(list)
for i in range(m):
x,y= map(int,input().split(' '))# x: 부모, y: 자식
graph[x].append(y)
graph[y].append(x)
# print('graph',graph)
def dfs(a,chon,visited):
childs=graph[a]
chon+=1
visited.append(a)
if b in childs: # 도착
print(chon)
exit()
else:
for child in childs:
if child not in visited:
dfs(child,chon,visited)
visited=[]
dfs(a,0,visited)
print(-1)
설명
- 촌수를 print한 후 프로그램을 끝내버리기 때문에 끝나지 않은 경우는 -1로 해서 코드를 줄일 수 있었다.
배운 점
- dictionary 에 양방향으로 넣는 방법을 처음에 생각하지 못했는데, 넣는 것이 훨씬 나은 것 같다.
'개발 > Algorithm' 카테고리의 다른 글
[Algorithm] 백준 BOJ 1463 1로 만들기 : python 파이썬 DP 실버 3 (0) | 2022.08.01 |
---|---|
[Algorithm] 백준 BOJ 11000 강의실 배정 : python 파이썬 그리디 골드 5 (0) | 2022.07.26 |
[Algorithm] 백준 BOJ 7576 토마토 python 파이썬 BFS 골드 5 / 메모리 초과 (0) | 2022.04.29 |
[Algorithm] 백준 BOJ 1260 DFS와 BFS python 파이썬 그래프 실버 2 (0) | 2022.04.23 |
[Algorithm] 백준 BOJ 2468 안전 영역 python 파이썬 그래프 실버 1 (0) | 2022.03.23 |