백준 1697 : 숨바꼭질 (파이썬)

Yibangwon·2022년 3월 12일
0

알고리즘 문제풀이

목록 보기
20/60


정답코드

N, K = map(int, input().split())

arr = []
visited = [False for i in range(150001)]
answer = 0

def bfs(start, depth):
    global answer
    arr.append([start, depth])
    visited[start] = True

    while len(arr) > 0:
        curr = arr[0][0]
        d = arr[0][1]
        del arr[0]

        next1, next2, next3 = curr * 2, curr + 1, curr - 1

        if next1 == K or next2 == K or next3 == K:
            answer = d + 1
            break

        if next1 < 150001 and not visited[next1]:
            visited[next1] = True
            arr.append([next1, d + 1])
        if next2 < 150001 and not visited[next2]:
            visited[next2] = True
            arr.append([next2, d + 1])
        if next3 >= 0 and not visited[next3]:
            visited[next3] = True
            arr.append([next3, d + 1])

if N!= K:
    bfs(N, 0)

print(answer)

문제유형

BFS

profile
I Don’t Hope. Just Do.

0개의 댓글