ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

๐Ÿšฉ ๊ทธ๋ž˜ํ”„ํƒ์ƒ‰, BFS

 

thinking

1. fail (๋ฉ”๋ชจ๋ฆฌ์ดˆ๊ณผ)

์ฒ˜์Œ ํ’€์—ˆ์„๋•Œ๋Š” N๊ณผ K์˜ ๋ฒ”์œ„๊ฐ€ ์ปค์„œ ๋ฐฉ๋ฌธ์ฒดํ‚น์„ ์ธ๋ฑ์Šค๋กœ ์ ‘๊ทผํ•˜๋Š” ๋ฆฌ์ŠคํŠธ๋กœ ์•ˆ ๋งŒ๋“ค๊ณ  ๋”•์…”๋„ˆ๋ฆฌ๋กœ ๋งŒ๋“ค์—ˆ๋Š”๋ฐ ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค.

๊ตฌ๊ธ€๋งํ•ด๋ณด๋‹ˆ, ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋ฐฉ๋ฌธํ–ˆ๋˜ ๋…ธ๋“œ๋„ ํ์— ๋‹ค์‹œ ๋„ฃ์–ด์ ธ์„œ ๊ทธ๋ ‡๋‹ค๊ณ  ํ•œ๋‹ค.


โญ ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ ๋ฐœ์ƒ ์ด์œ  : 

๊ณผ๊ฑฐ์— ํ–ˆ๋˜ ๊ฐ’์„ ๊ณ„์† ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ํ์— ๊ฐ’์„ ๋„ฃ๋Š” ๊ฒƒ ๋•Œ๋ฌธ์— ๋ฐœ์ƒํ•จ.

ex. 10์—์„œ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋…ธ๋“œ: 9, 11, 20. but, 10๊นŒ์ง€ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ• ์—„์ฒญ ๋งŽ์Œ. (9->10, 11->10, 5->10 ... )

 

2. success ๐Ÿ˜€

๋ฐฉ๋ฌธ์ฒดํ‚น ๋ฆฌ์ŠคํŠธ๋ฅผ ์ธ๋ฑ์Šค๋กœ ์ ‘๊ทผํ•ด 100,001 ๊ฐœ์˜ ์นธ์œผ๋กœ ๋งŒ๋“ค์–ด์คฌ๋‹ค. ์นธ์ด 10๋งŒ๊ฐœ ์žˆ์–ด๋„ ์•„๋ฌด๋Ÿฐ ์ƒ๊ด€์—†๋‹ค.

๊ดœํžˆ ์ˆซ์ž ์ปค์ง€๊ณ  for๋ฌธ ๋งŽ์•„์ง€๋ฉด ์ซ„๊ฒŒ๋œ๋‹ค.. ์ซ„์ง€๋ง์ž

์ด๋•Œ ์ฃผ์˜ํ• ๊ฑด 19๋ฒˆ์งธ ์ค„์—   if 0<=v<=100000:   ์กฐ๊ฑด์„ ์„ค์ •ํ•ด์•ผํ•œ๋‹ค !

์™œ๋ƒ๋ฉด x๊ฐ€ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ๊ฐ’์ด x-1, x+1, x² ์ธ๋ฐ ๋™์ƒ ์œ„์น˜์˜ ๋ฒ”์œ„๊ฐ€ 0 ≤ K ≤ 100,000 ์ด๋ฏ€๋กœ x-1, x+1, x² ๊ฐ’๋“ค์€ 0~100,000 ์‚ฌ์ด์— ์žˆ์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

์ฝ”๋“œ

from collections import deque


def bfs(x):
    global res
    q = deque()
    q.append(x)
    visited = [0]*100001
    visited[x] = 1

    while q:
        x = q.popleft()
        if x == K:
            res = visited[x]-1
            return
        tmp = []  # ์—ฐ๊ฒฐ๋…ธ๋“œ ๋‹ด์„ ์ž„์‹œ ๋ฆฌ์ŠคํŠธ
        tmp.extend([x - 1, x + 1, 2 * x])
        for v in tmp:
            if 0<= v <=100000:  # ๋Ÿฐํƒ€์ž„์—๋Ÿฌ(out of range) ๋ฐฉ์ง€์šฉ ๋ฒ”์œ„์„ค์ •
                if not visited[v]:  # ๋ฐฉ๋ฌธ ์•ˆํ–ˆ์œผ๋ฉด ๋ฐฉ๋ฌธ์ฒดํฌ
                    visited[v] = visited[x]+1
                    q.append(v)
        tmp = []  # ์ดˆ๊ธฐํ™”


N, K = map(int, input().split())  # N:์ˆ˜๋นˆ, K:๋™์ƒ
res = 0
bfs(N)
print(res)

 

 

ํ•œ์ค„ํ‰

์‹ค๋ฒ„ 1์„ ๋ณด๊ณ  ์‹คํŒจ๊ฐ์ด๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ํŒจ์“ฐํ•ด์„œ ํ–‰๋ณตํ•˜๋‹ค ๐Ÿ˜€

 

๋Œ“๊ธ€