forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1.py
More file actions
37 lines (31 loc) Β· 1.08 KB
/
1.py
File metadata and controls
37 lines (31 loc) Β· 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from collections import deque
# λμμ κ°μ, λλ‘μ κ°μ, 거리 μ 보, μΆλ° λμ λ²νΈ
n, m, k, x = map(int, input().split())
graph = [[] for _ in range(n + 1)]
# λͺ¨λ λλ‘ μ 보 μ
λ ₯ λ°κΈ°
for _ in range(m):
a, b = map(int, input().split())
graph[a].append(b)
# λͺ¨λ λμμ λν μ΅λ¨ 거리 μ΄κΈ°ν
distance = [-1] * (n + 1)
distance[x] = 0 # μΆλ° λμκΉμ§μ 거리λ 0μΌλ‘ μ€μ
# λλΉ μ°μ νμ(BFS) μν
q = deque([x])
while q:
now = q.popleft()
# νμ¬ λμμμ μ΄λν μ μλ λͺ¨λ λμλ₯Ό νμΈ
for next_node in graph[now]:
# μμ§ λ°©λ¬Ένμ§ μμ λμλΌλ©΄
if distance[next_node] == -1:
# μ΅λ¨ 거리 κ°±μ
distance[next_node] = distance[now] + 1
q.append(next_node)
# μ΅λ¨ κ±°λ¦¬κ° KμΈ λͺ¨λ λμμ λ²νΈλ₯Ό μ€λ¦μ°¨μμΌλ‘ μΆλ ₯
check = False
for i in range(1, n + 1):
if distance[i] == k:
print(i)
check = True
# λ§μ½ μ΅λ¨ κ±°λ¦¬κ° KμΈ λμκ° μλ€λ©΄, -1 μΆλ ₯
if check == False:
print(-1)