728x90
반응형
https://www.acmicpc.net/problem/16397
16397번: 탈출
첫 번째 줄에 N (0 ≤ N ≤ 99,999), T (1 ≤ T ≤ 99,999), G (0 ≤ G ≤ 99,999)가 공백 하나를 사이에 두고 주어진다. 각각 N은 LED로 표현된 수, T는 버튼을 누를 수 있는 최대 횟수, G는 탈출을 위해 똑같이
www.acmicpc.net
최종 코드
GitHub - hwayeon351/BEAKJOON-Algorithms: 백준 알고리즘 소스 코드 모음
백준 알고리즘 소스 코드 모음. Contribute to hwayeon351/BEAKJOON-Algorithms development by creating an account on GitHub.
github.com
import sys, math
from collections import deque
def press_btn():
visit = [0]*100000
visit[N] = 1
q = deque([[N, 0]])
while q:
n, cnt = q.popleft()
if n == G:
print(cnt)
return
if cnt == T: continue
if n+1 <= 99999 and not visit[n+1]:
visit[n+1] = 1
q.append([n+1, cnt+1])
if 0 < n*2 <= 99999:
new = n*2 - (10**int(math.log10(n*2)))
if not visit[new]:
visit[new] = 1
q.append([new, cnt+1])
print("ANG")
input = sys.stdin.readline
N, T, G = map(int, input().split())
press_btn()
풀이 과정
풀이 시간 16분
import sys, math
from collections import deque
def press_btn():
#만든 숫자 방문 처리
visit = [0]*100000
visit[N] = 1
q = deque([[N, 0]])
while q:
n, cnt = q.popleft()
#G와 숫자가 같아지면 버튼 횟수를 출력하고 함수 종료
if n == G:
print(cnt)
return
#T번 버튼을 눌렀는데 G와 같지 않은 경우, 더이상 버튼을 누르지 않는다
if cnt == T: continue
#버튼 A 누르기
if n+1 <= 99999 and not visit[n+1]:
visit[n+1] = 1
q.append([n+1, cnt+1])
#버튼 B 누르기
if 0 < n*2 <= 99999:
new = n*2 - (10**int(math.log10(n*2)))
if not visit[new]:
visit[new] = 1
q.append([new, cnt+1])
#모든 경우의 수로 버튼을 눌렀는데도 G를 만들 수 없는 경우, 탈출 불가
print("ANG")
input = sys.stdin.readline
N, T, G = map(int, input().split())
press_btn()
#시간복잡도 = O(V+E), 공간복잡도 = O(n)
728x90
반응형
'코테 노트 > 백준' 카테고리의 다른 글
백준 1525 퍼즐 Python 3 (0) | 2022.02.10 |
---|---|
백준 1039 교환 Python 3 (0) | 2022.02.09 |
백준 2206 벽 부수고 이동하기 Python 3 (0) | 2022.02.08 |
백준 3055 탈출 Python 3 (0) | 2022.02.08 |
백준 5427 불 Python 3 (0) | 2022.02.07 |