알고리즘

파이썬)A -> B -BOJ

1일1공부실천하자 2023. 8. 13. 23:34

 

https://www.acmicpc.net/problem/16953

 

 

16953번: A → B

첫째 줄에 A, B (1 ≤ A < B ≤ 109)가 주어진다.

www.acmicpc.net

 

 

from collections import deque

a, b = map(int, input().split())

r = 1


def bfs(a, b):
    q = deque()
    q.append((a, 1))

    while q:
        a, count = q.popleft()

        if a == b:
            print(count)
            return

        if a * 2 <= b:
            q.append((a * 2, count + 1))
        if a * 10 + 1 <= b:
            q.append((a * 10 + 1, count + 1))
    print(-1)


bfs(a, b)

bfs를 이용해 풀었다.