[Baekjoon] 13549 숨바꼭질(3) python

sorzzzzy·2021년 8월 4일
0

Baekjoon Algorithm

목록 보기
20/46
post-thumbnail

🏷 문제


💡 코드

from collections import deque

def find(n, k):
    visited = [False] * 100001
    cnt = [-1] * 100001
    visited[n] = True
    cnt[n] = 0
    q = deque()
    q.append(n)
    while q:
        target = q.popleft()
        if target == k:
            return cnt[target]
        # 순간이동 하는 경우
        if 0 <= target*2 < 100001 and visited[target*2] == False:
            q.append(target*2)
            cnt[target*2] = cnt[target]
            visited[target*2] = True
        # 걷는경우(+1)
        if 0 <= target+1 < 100001 and visited[target+1] == False:
            q.append(target+1)
            cnt[target+1] = cnt[target]+1
            visited[target+1] = True
        # 걷는경우(-1)
        if 0 <= target-1 < 100001 and visited[target-1] == False:
            q.append(target-1)
            cnt[target-1] = cnt[target]+1
            visited[target-1] = True
        
n, k = map(int, input().split())
res = find(n, k)
print(res)

🔑

profile
Backend Developer

0개의 댓글