https://www.acmicpc.net/problem/9019
문제를 보고, 이 문제도 BFS로 풀 수 있겠다. 라고 생각하고 BFS로 풀어나갔다.
시간 제한이 6초여서 모든 경우의 수를 queue에 넣어가도 괜찮을 거라고 생각했다.
from collections import deque
t = int(input())
def bfs(a,b):
queue = deque([(a,"")])
cnt = 0
visited = [False] * 10000
visited[int(a)] = True
while True:
length = len(queue)
for _ in range(length):
da, cmd = queue.popleft()
#A와 B가 같아질 경우
if da == b:
print(cmd)
return
else:
#1.D
temp = (2*int(da)) % 10000
if not visited[temp]:
visited[temp] = True
queue.append((str(temp),cmd+"D"))
#2.S
if da == "0":
temp = 9999
else:
temp = int(da) - 1
if not visited[temp]:
visited[temp] = True
queue.append((str(temp),cmd+"S"))
# 3. L 명령어 (왼쪽 회전)
current_str = str(da).zfill(4) # 4자리 문자열로 변환
next_l = int(current_str[1:] + current_str[0])
if not visited[next_l]:
visited[next_l] = True
queue.append((str(next_l), cmd + "L"))
# 4. R 명령어 (오른쪽 회전)
next_r = int(current_str[-1] + current_str[:-1])
if not visited[next_r]:
visited[next_r] = True
queue.append((str(next_r), cmd + "R"))
for _ in range(t):
a,b = map(str, input().split())
bfs(a,b)
D,S,L,R의 기능을 각각 수행해서 queue에 담는다.
이것을 A와 B가 같을 때 까지 계속해서 반복한다.
처음엔 visited 없이 중복되는 수도 queue에 넣었다가 메모리 초과가 되어, 이미 방문한 수는 다시 방문하지 못하게 하였다.
이제 BFS 문제는 자신감이 조금 생긴 것 같다!
'백준' 카테고리의 다른 글
[백준] 15649번: N과M(1), 15650번 N과M(2) (파이썬) (1) | 2025.01.09 |
---|---|
[백준] 7662번: 이중 우선순위 큐(파이썬) (0) | 2025.01.08 |
[백준] 14500번: 테트로미노 (파이썬) (0) | 2025.01.06 |
[백준] 16928번: 뱀과 사다리 게임 (파이썬) (2) | 2025.01.06 |
[백준] 5430번: AC (파이썬) (1) | 2025.01.01 |