๐ algorithm/boj
BOJ 16397 - ํ์ถ
HandHand
2021. 3. 18. 16:36
๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 16397๋ฒ
ํ์ด ๊ณผ์
BFS
๋ฅผ ํตํด ๋ชฉํ ์ซ์์ ๋๋ฌํ๊ธฐ ์ํ ์ต์ ๋ฒํผ ํ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์
๋๋ค.
๊ฐ๊ฐ์ ๋ฒํผ์ ๋๋ฅผ ์ ์๋ ์กฐ๊ฑด์ด ์ฃผ์ด์ ธ ์์ผ๋ฏ๋ก ์ด๋ฅผ ๊ธฐ์ค์ผ๋ก ํ์์ ์ํํ๋ฉด๋ฉ๋๋ค.
์ซ์์ ๋ํ ์ฐ์ฐ(๋งจ ์์๋ฆฌ ๊ฐ์)์ Python์ ์ฌ๋ผ์ด์ฑ์ ํ์ฉํ๋ฉด ์ฝ๊ฒ ๊ตฌํํ ์ ์์ต๋๋ค.
์ฝ๋
import sys
from collections import deque
N, T, G = list(map(int, sys.stdin.readline().split()))
INF = 100000
def bfs(start):
q = deque()
visit = [0 for _ in range(INF)]
q.append((start, 0))
visit[start] = 1
while q:
here, cost = q.popleft()
if cost > T:
return 'ANG'
if here == G:
return cost
# A ๋ฒํผ์ ๋๋ฅธ ๊ฒฝ์ฐ
if here+1 < INF and not visit[here+1]:
q.append((here+1, cost+1))
visit[here+1] = 1
# B ๋ฒํผ์ ๋๋ฅธ ๊ฒฝ์ฐ
if here*2 < INF:
temp = str(here*2)
if int(temp) != 0:
temp = str(int(temp[0])-1) + temp[1:]
if not visit[int(temp)]:
q.append((int(temp), cost+1))
visit[int(temp)] = 1
return 'ANG'
def solution():
ans = bfs(N)
return ans
print(solution())
๋ฐ์ํ