문제 링크 : https://www.acmicpc.net/problem/5014
최소 이동 수를 구할 때 dfs로 풀이했을 때는 이동할 수 있는 경우의 cnt를 전부 구하고 또 그 최솟값을 구해야 하기 때문에 비효율적이라고 생각했다.
또한 주어지는 변수의 범위가 매우 크므로 (1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000) bfs를 이용하여 풀이하였다.
1<=next<=floor
), 방문 확인(v[n]=0
)v[next] = v[now]+1
, q.append(next)
저장된 값 -1
리턴 (처음에 1부터 시작했으므로!)use the stairs
출력from collections import deque
# 건물 층수, 현재 위치, 도착 위치, 위로, 아래로
floor, st, ed, up, down = map(int, input().split())
visited = [0]*(floor+1)
flag = 0
def bfs():
global flag
q = deque()
q.append(st)
visited[st] = 1
while q:
now = q.popleft()
for d in (up, -down):
Next = now + d
if 1 <= Next <= floor:
if visited[Next] == 0:
visited[Next] = visited[now] + 1
q.append(Next)
# 오답 원인
if Next == ed:
flag = 1
return visited[Next] - 1
answer = bfs()
if flag == 1:
print(answer)
else:
print('use the stairs')
from collections import deque
# 건물 층수, 현재 위치, 도착 위치, 위로, 아래로
floor, st, ed, up, down = map(int, input().split())
visited = [0]*(floor+1)
flag = 0
def bfs():
global flag
q = deque()
q.append(st) # 시작 위치 담고
visited[st] = 1 # 방문 체크
while q:
now = q.popleft()
if now == ed: # 도착하면
flag = 1 # flag 켜기
return visited[now] - 1 # 시작할 때 1부터 시작했으므로
for d in (up, -down): # 위로, 아래로 2방향 탐색
Next = now + d
if 1 <= Next <= floor: # 범위 확인
if visited[Next] == 0:
visited[Next] = visited[now] + 1
q.append(Next)
answer = bfs()
if flag == 1:
print(answer)
else:
print('use the stairs')
from collections import deque
# 건물 층수, 현재 위치, 도착 위치, 위로, 아래로
floor, st, ed, up, down = map(int, input().split())
visited = [0]*(floor+1)
def bfs():
q = deque()
q.append(st) # 시작 위치 담고
visited[st] = 1 # 방문 체크
while q:
now = q.popleft()
if now == ed: # 도착하면
return visited[now] - 1 # 시작할 때 1부터 시작했으므로
for d in (up, -down): # 위로, 아래로 두 방향 탐색
Next = now + d
if 1 <= Next <= floor:
if visited[Next] == 0:
visited[Next] = visited[now] + 1
q.append(Next)
return 'use the stairs'
print(bfs())
return
을 잘 활용하자!