알고리즘💻/그래프(DFS&BFS)

BOJ 5014: 스타트 링크

호프 2023. 9. 15. 01:33

https://www.acmicpc.net/problem/5014

 

5014번: 스타트링크

첫째 줄에 F, S, G, U, D가 주어진다. (1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000) 건물은 1층부터 시작하고, 가장 높은 층은 F층이다.

www.acmicpc.net

아파트 층을 한 방향으로 연결된 그래프(리스트) 라고 생각을 하고 BFS로 풀면 간단히 풀 수 있는 문제이다.

graph 배열을 만들어서 INF로 채워넣고, 처음 방문하게 되면 이전 위치의 값에서 1을 더한 값을 저장했다. 

import sys
from collections import deque
input = sys.stdin.readline

F, S, G, U, D = map(int, input().split())
INF = 10**9
graph = [INF for _ in range(F)]

graph[S-1] = 0
dx = [U, -D]

def bfs(x):
    queue = deque()
    graph[x] = 0
    queue.append(x)
    while queue:
        v = queue.popleft()
        for i in range(2):
            nx = v + dx[i]
            if (nx >= 0 and nx < F and graph[nx] == INF):
                graph[nx] = graph[v] + 1
                queue.append(nx)
    return graph[G-1]

ans = bfs(S-1)
if (ans == INF): print('use the stairs')
else: print(ans)