본문 바로가기
알고리즘/BOJ

[BOJ / 백준] 5014 스타트링크 python / 파이썬 bfs

by seohmoon 2023. 7. 11.

출처 : 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


1) 요구사항 분석 : 문제 읽기

G층에 도착하려면, 버튼을 적어도 몇 번 눌러야 하는지 구하는 프로그램

 

2) 설계 : 접근 방식

U버튼, D버튼을 눌렀을 때 배열의 범위 안에 들어있는지 체크하는 함수를 만들어줌

bfs 함수를 만들어주는데 두번째 반복문을 종료할때마다 x의 크기를 +1 해줌

 

만약 실행결과가 False이면 계단을 이용~

 

from collections import deque
que = deque()
F, S, G, U, D = map(int, input().split())

visited = [False for _ in range(F + 1)]

def in_range(x):
    return 1 <= x <= F

def bfs():
    global ans
    global flag
    while len(que) > 0:
        size = len(que)
        for _ in range(size):
            tem = que.popleft()
            for i in [U, - D]:
                nx = tem + i
                if in_range(nx) and visited[nx] == False:
                    visited[nx] = True
                    que.append(nx)
                    if nx == G:
                        return True
        ans += 1

que.append(S)
visited[S] = True
ans = 0
flag = 0
if S == G:
    print(ans)
else:
    ans += 1
    if bfs():
        print(ans)
    else:
        print("use the stairs")

댓글