DevYoon

[๋ฐฑ์ค€] 13549. ์ˆจ๋ฐ”๊ผญ์งˆ3 (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 13549. ์ˆจ๋ฐ”๊ผญ์งˆ3 (Python)

gimewn 2022. 5. 17. 15:38

link ๐Ÿ”— https://www.acmicpc.net/problem/13549

 

13549๋ฒˆ: ์ˆจ๋ฐ”๊ผญ์งˆ 3

์ˆ˜๋นˆ์ด๋Š” ๋™์ƒ๊ณผ ์ˆจ๋ฐ”๊ผญ์งˆ์„ ํ•˜๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ํ˜„์žฌ ์  N(0 ≤ N ≤ 100,000)์— ์žˆ๊ณ , ๋™์ƒ์€ ์  K(0 ≤ K ≤ 100,000)์— ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ๊ฑท๊ฑฐ๋‚˜ ์ˆœ๊ฐ„์ด๋™์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ, ์ˆ˜๋นˆ์ด์˜ ์œ„์น˜๊ฐ€ X์ผ

www.acmicpc.net

 

๐Ÿ’ซ ๊ฑธ์–ด์„œ ๊ฐˆ ๋•Œ๋ณด๋‹ค ์ˆœ๊ฐ„์ด๋™์œผ๋กœ ๊ฐˆ ๋•Œ ์‹œ๊ฐ„์ด ๋” ์ ๊ฒŒ ๊ฑธ๋ฆผ โžก๏ธ appendleft๋กœ ๋จผ์ € ๋„ฃ์–ด์ฃผ๊ธฐ

 

from collections import deque

def BFS(start, target):
    q = deque()
    q.append((start, 0)) # start, cnt
    Mincnt = 0
    check = [0]*100001
    while q:
        now, cnt = q.popleft()

        if now == target:
            Mincnt = cnt
            break

        path = [now-1, now+1, now*2]

        for p in path:
            if 0<= p <= 100000 and check[p] == 0:
                check[p] = 1
                if p == now*2:
                    q.appendleft((p, cnt))
                else:
                    q.append((p, cnt+1))

    return Mincnt

n, k = map(int, input().split())

res = BFS(n, k)

print(res)