근데 공식을 생각할 수록, 난잡하게 짜여지길래 bfs로 풀어야한다고 생각했다.
N과 K의 값의 조건은 0과 100,000 사이라고만 주어졌다, 즉, N이 K보다 클수도, 작을 수도 있는 상황이라는 것도 참고해서 그래프로 풀어야겠다는 생각을 했다.
bfs에서 무한루프를 돌지 않게 하기 위한 조건문을 정한다.
조건문만 잘 선택했다면 아래와 같이 구현할 수 있다.
import sys
from collections import deque
N,K = list(map(int, sys.stdin.readline().strip().split()))
MAXCOUNT = 100001
current_map = [MAXCOUNT] * MAXCOUNT
def bfs(start, target):
current = deque([start])
current_map[start] = 0
options = [-1,1,2]
while current:
node = current.popleft()
for option in options:
examine_node = option+node if option!=2 else option*node
if 0<= examine_node < MAXCOUNT:
temp, current_map[examine_node] = current_map[examine_node], min(current_map[node]+1, current_map[examine_node])
if temp != current_map[examine_node] and examine_node!=target:
current.append(examine_node)
bfs(N,K)
print(current_map[K])