λ¬Έμ
https://www.acmicpc.net/problem/13549
νμ΄
# λ°±μ€ 13549λ² λ¬Έμ - μ¨λ°κΌμ§ 3
from collections import deque
# 0 - 1 bfs νμ
def bfs():
graph = [-1] * 100001
graph[n] = 0
queue = deque([n])
while queue:
target = queue.popleft()
# λμμ μμΉμ λλ¬νλ€λ©΄ 리ν΄
if target == k:
return graph[target]
# λ°λ³΅λ¬Έμ ν΅ν΄ 3κ°μ§ μ΄λμ κ²½μ°λ₯Ό νμΈ
for i in (target + 1, target - 1, target * 2):
# μ΄λνλ κ³³μ΄ λ²μ λ΄μ μκ³ μ΄λνμ§ μμλ€λ©΄ μ΄λ
if 0 <= i <= 100000 and graph[i] == -1:
# μκ°μ΄λμ΄λΌλ©΄
if i == target * 2:
graph[i] = graph[target] # 0μ΄ κ°±μ
queue.appendleft(i) # μκ°μ΄λμ΄κΈ°μ λ¨Όμ νμ
else:
graph[i] = graph[target] + 1
queue.append(i)
n, k = map(int, input().split())
print(bfs())
'ποΈ Algorithm > π© λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
π© [λ°±μ€] [Python] [Gold5] 1068λ²_νΈλ¦¬ (0) | 2023.01.04 |
---|---|
π© [λ°±μ€] [Python] [Gold4] 2573λ²_λΉμ° (0) | 2023.01.04 |
π© [λ°±μ€] [Python] 24444λ²_μκ³ λ¦¬μ¦ μμ - λλΉ μ°μ νμ 1 (0) | 2022.12.16 |
π© [λ°±μ€] [Python] 24445λ²_μκ³ λ¦¬μ¦ μμ - λλΉ μ°μ νμ 2 (0) | 2022.12.16 |
π© [λ°±μ€] [Python] 16234λ²_μΈκ΅¬ μ΄λ (0) | 2022.12.16 |