Skip to content

Commit 03a66b3

Browse files
authored
[BOJ] 2644 촌수 계산 (S2)
1 parent 953320f commit 03a66b3

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

김지호/8주차/260219.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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)

0 commit comments

Comments
 (0)