File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ [BOJ] #2644. 촌수계산 / 실버2
3+
4+ 할아버지 - 아빠 - 나
5+ 할아버지 - 그외 기타 등등
6+ - 촌수 = X <-> Y 까지 거리
7+ """
8+ import sys
9+ from collections import deque
10+ input = sys .stdin .readline
11+
12+ #1. 입력 변수
13+ # 인접 리스트 만들기(양방향)
14+
15+ N = int (input ())
16+ nodes = [[] for _ in range (N + 1 )]
17+ tx , ty = map (int , input ().split ())
18+
19+
20+ M = int (input ())
21+ for _ in range (M ):
22+ x ,y = map (int ,input ().split ())
23+ nodes [x ].append (y )
24+ nodes [y ].append (x )
25+
26+ # 2.x -> y 의 최단 거리 찾기 : BFS
27+ # 거리 = level
28+ q = deque ([[tx , 0 ] ])
29+ visited = []
30+ answer = - 1
31+ while q :
32+ cn , cl = q .popleft ()
33+ if cn == ty : # target 값에 도달할때만 촌수를 answer에 업데이트 하기
34+ answer = cl
35+ break
36+ for nn in nodes [cn ]: # 인접 리스트 찾기
37+ if nn not in visited :
38+ visited .append (nn )
39+ q .append ([nn ,cl + 1 ] )
40+
41+ # print(visited)
42+ print (answer )
You can’t perform that action at this time.
0 commit comments