[BaekJoon] λ°±μ€€ 16953번 : A to B

Updated:

16953번 : A β†’Β B


μ–΄λ–€ μž‘μ—…μ„ ν•΄ λ‚˜κ°€λ©΄μ„œ κ·Έ μž‘μ—… 횟수의 μ΅œμ†Œλ₯Ό λ¬Όμ–΄λ³Έλ‹€λ©΄..

κ·Έλž˜ν”„λ₯Ό κ·Έλ € νƒμƒ‰ν•˜λ©΄ λœλ‹€..


image

μ΅œλŒ€ 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)



Categories:

Updated:

Leave a comment