순간이동의 경우 시간 소모가 0초이다.
따라서 스택과 큐를 이용하여 그래프를 순회하게 될 경우에는 최단거리를 찾을 수 없게 된다.
그래서 떠올린 것이 우선순위 큐이다.
우선순위 큐를 이용하여 순간이동을 우선적으로 탐색하여 최단거리를 찾을 수 있었다.
from queue import PriorityQueue
N, K = map(int, input().split(" "))
def BFS(start, end):
queue = PriorityQueue()
queue.put((0, start))
visited = [int(0) for _ in range(100001)]
while queue:
cost,now = queue.get()
if now == end:
return cost
visited[now] = 1
if now * 2 <= 100000 and visited[now*2] == 0:
queue.put(( cost, now*2 ))
if now -1 >= 0 and visited[now-1] == 0:
queue.put((cost +1,now-1 ))
if now +1 <= 100000 and visited[now+1] == 0:
queue.put((cost +1,now+1 ))
print(BFS(N,K))
'백준' 카테고리의 다른 글
[백준 1987] 알파벳 (python) (0) | 2023.04.05 |
---|---|
[백준 25757] 임스와 함께하는 미니게임 python(시간초과) (0) | 2023.01.04 |
[백준 4659] 비밀번호 발음하기 python (50%에서 틀림) (0) | 2023.01.02 |
[백준 20055] 컨베이어 벨트 위의 로봇(python) deque 이용 구현 (0) | 2023.01.01 |
[백준 3190] 뱀 python (tc5 tc6 틀림) (3) | 2022.12.23 |