[BaekJoon] λ°±μ€ 16953λ² : A to B
Updated:
16953λ² : A βΒ B
μ΄λ€ μμ μ ν΄ λκ°λ©΄μ κ·Έ μμ νμμ μ΅μλ₯Ό λ¬Όμ΄λ³Έλ€λ©΄..
κ·Έλνλ₯Ό κ·Έλ € νμνλ©΄ λλ€..
μ΅λ 109 κΉμ§ κ°λ₯νκΈ° λλ¬Έμ 미리 κ·Έλνλ₯Ό κ·Έλ €λκ³ νμνκΈ° λ³΄λ€ λ§λ€μ΄ κ°λ©΄μ νμμ νλ©΄ λλ€.
νμ μ μ₯ν λ μ°μ° νμλ ν¨κ» μ μ₯μ ν΄μ£Όλ©΄ λλ€.
μ°μ°μ νΉμ± μ νΈλ¦¬κ° μμ± λκΈ° λλ¬Έμ λ°©λ¬Έ λ Έλλ₯Ό λ°λ‘ κ΄λ¦¬ ν νμλ μλ€.
from collections import deque
def solution(start, goal):
cnt = 1
queue = deque([[start, cnt]])
while queue:
curNode, curCnt = queue.popleft()
if curNode == goal:
print(curCnt)
return
leftChild = curNode * 2
rightChild = curNode * 10 + 1
if leftChild <= 10**9:
queue.append([leftChild, curCnt + 1])
if rightChild <= 10**9:
queue.append([rightChild, curCnt + 1])
else:
print(-1)
return
n, m = map(int, input().split())
solution(n, m)
Leave a comment