File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://www.acmicpc.net/problem/2644
2+ # 촌수 계산, 실버2
3+
4+ import sys
5+ from collections import deque , defaultdict
6+
7+ sys .stdin = open ('../input.txt' , 'r' )
8+
9+ N = int (input ()) # 사람의 수
10+ start ,end = map (int ,input ().split (" " )) # 촌수 계산해야 하는 사이
11+ M = int (input ()) # 관계의 수
12+
13+ def get_answer (start ,end , N , M ):
14+ graph = defaultdict (list )
15+ for _ in range (M ):
16+ s ,e = map (int ,input ().split (" " ))
17+ graph [s ].append (e )
18+ graph [e ].append (s )
19+
20+ visited = [False ] * (N + 1 )
21+ queue = deque ()
22+
23+ queue .append ((start ,0 ))
24+ visited [start ] = True
25+
26+ while (len (queue ) != 0 ):
27+ # print(f"queue: {queue}")
28+ node , length = queue .popleft ()
29+
30+ # 정답
31+ if (node == end ):
32+ return length
33+
34+ for next_node in graph [node ]:
35+ # 정답
36+ if next_node == end :
37+ return length + 1
38+
39+ if not visited [next_node ]:
40+ queue .append ((next_node , length + 1 ))
41+ visited [next_node ] = True
42+
43+ return - 1 # 촌수 관계 없는 경우
44+
45+
46+
47+ answer = get_answer (start ,end , N , M )
48+ print (answer )
You can’t perform that action at this time.
0 commit comments