[알고리즘] 백준 5014 스타트링크

CHOI IN HO·2024년 4월 8일
0

코딩테스트

목록 보기
71/74

풀이

해당문제는 bfs문을 짜는데는 어렵지 않지만 가지치기 즉 시간을 줄이는 곳에서 고민이 필요하다.

import sys
from collections import deque

f, s, g, u, d = map(int, input().split())
visited = [False] * (f+1)

def bfs(f,s,g,u,d):
    q = deque()
    q.append((s, 0))

    while q:
        now, count  = q.popleft()
        if count > 1000000:
            return 'use the stairs'
        if now == g:
            return count
        # 위층을 누르는 경우
        if now+u <= f and u != 0 and visited[now+u] == False:
            visited[now+u] = True
            q.append((now+u, count+1))
        # 아래층을 누르는 경우
        if now-d >= 1 and d != 0 and visited[now - d] == False:
            visited[now - d] = True
            q.append((now-d, count+1))

    return 'use the stairs'

print(bfs(f,s,g,u,d))
profile
개발자기 되기 위해선 무엇이든!

0개의 댓글