๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[๋ฐฑ์ค 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))