[๋ฐฑ์ค€-1697] ์ˆจ๋ฐ”๊ผญ์งˆ / Python

๐Ÿ“š Problem Solving/Baekjoon

https://www.acmicpc.net/problem/1697

 

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

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

www.acmicpc.net

from collections import deque

n, k = map(int, input().split())
graph = [0] * 100001

dx = [-1, 1, 2]


def bfs(start):
    queue = deque()
    queue.append(start)
    while queue:
        x = queue.popleft()
        if x == k:
            print(graph[x])
            break
        for i in range(3):
            if i == 2:
                nx = x * dx[i]
            else:
                nx = x + dx[i]
            if 0 <= nx < 100001 and graph[nx] == 0:
                graph[nx] = graph[x] + 1
                queue.append(nx)


bfs(n)

ํ•ด์„ค

์ด ๋ฌธ์ œ๋„ ๋”ฑํžˆ ์–ด๋ ต์ง€๋Š” ์•Š์•˜๋‹ค. ์‹œ์ž‘ ์œ„์น˜๋กœ๋ถ€ํ„ฐ -1, 1, ์‹œ์ž‘์œ„์น˜*2 ๋งŒํผ ์ด๋™ํ•˜๋ฉด์„œ ๊ฐ’์„ ์ด์ „ ๊ฐ’์— 1์”ฉ ์ฆ๊ฐ€์‹œ์ผœ์คฌ๋‹ค.