- bfs를 이용하여 구현하였다.
from collections import deque
N,M = map(int,input().split())
q = deque([(N,0)])
used = [0] * 100001
def bfs():
while q:
n,c = q.popleft()
if 0 <= n <= 100000: # 동생의 최소, 최대 인덱스값을 벗어나지 않아야함
if used[n] == 0: # used배열을 통해 왔던곳은 가지 않으며 시간 단축
used[n] += 1
else:
continue
if n == M:
print(c)
break
q.append([n-1,c+1])
q.append([n+1,c+1])
q.append([n*2,c+1])
bfs()
'Python > 백준' 카테고리의 다른 글
[백준/Python] 2178 미로 탐색 (2) | 2022.09.29 |
---|---|
[백준/Python] 2606 바이러스 (0) | 2022.09.29 |
[백준/Python] 2667 단지번호붙이기 (0) | 2022.09.29 |
[백준/Python] 7576 토마토 (0) | 2022.09.29 |
[백준/Python] 1012 유기농 배추 (0) | 2022.09.29 |