ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

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

์€์ง„ 2021. 8. 3. 13:33

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

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

โœ๏ธIdea Sketch

2021-07-28

1. ์  N์˜ ๋ฒ”์œ„ (0 โ‰ค N โ‰ค 100,000)

  • visited๋Š” ํฌ๊ธฐ๊ฐ€ 100001์ธ ๋ฐฐ์—ด
visited = [0]*100001  # ๋ฐฉ๋ฒ•1
visited = [0 for i in range(100001)]  # ๋ฐฉ๋ฒ•2

2. ์†Œ์š” ์‹œ๊ฐ„ ์นด์šดํŠธํ•˜๋Š” ๋ฐฉ๋ฒ•

visited[i] = visited[v] + 1

3. ์  N ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌํ•  ํ•„์š” ์—†์Œ

  • N์„ ๋‹ค์‹œ ๋ฐฉ๋ฌธํ•˜๋Š” ๊ฒฝ๋กœ๋Š” ์–ด์ฐจํ”ผ ์ตœ๋‹จ๊ฒฝ๋กœ๊ฐ€ ์•„๋‹˜
def bfs(N, K, visited):
  queue = deque([N])
  visited[N] = 1  # ๋ถˆํ•„์š”


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-07-28 156ms ํ†ต๊ณผ

import sys
from collections import deque

N, K = map(int, sys.stdin.readline().split(' '))
visited = [0 for i in range(100001)]

def bfs(N, K, visited):
  queue = deque([N])
  while queue:
    v = queue.popleft()
    if v == K:
      return visited[K];
    for i in (v-1, v+1, v*2):
      if (-1<i<100001) and not visited[i]:
        queue.append(i)
        visited[i] = visited[v] + 1

print(bfs(N, K, visited))