[백준] 5014 - 스타트링크
1. 문제
2. 개요
특수한 엘리베이터를 이용해 스타트링크 사무실에 가려고 한다.
스타트링크는 F층 건물의 G층에 위치해 있으며 시작은 S층에서 한다.
엘리베이터는 특수해서 U칸 위로 올라가는 버튼과 D칸 아래로 내려가는 버튼만 존재한다.
이 때 스타트링크 사무실에 엘리베이터로 가장 빨리 도착하기 위해 버튼을 누르는 최소횟수를 구하는 문제. 엘리베이터로 도착할 수 없다면 use the stairs를 출력한다.
3. 풀이 및 코드
3-1. 풀이
기본적인 BFS문제. F까지의 visited배열을 만들고 현 위치에서 +U -D를 하며 방문처리를 해가는 BFS를 실행한 뒤 visited[G]의 값을 확인해 답을 출력한다.
3-2. Python
import sys
from collections import deque
F, S, G, U, D = map(int, sys.stdin.readline().split())
move = [U, -D]
visited = [-1 for i in range(F+1)]
visited[S] = 0
q = deque([S])
while q and visited[G] == -1:
now = q.popleft()
for i in range(2):
nxt = now + move[i]
if nxt < 1 or nxt > F:
continue
if visited[nxt] != -1:
continue
visited[nxt] = visited[now] + 1
q.append(nxt)
print(visited[G]) if visited[G] != -1 else print("use the stairs")
3-3. C#
namespace boj_5014
{
internal class Program
{
static void Main(string[] args)
{
int[] info = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
int F = info[0];
int S = info[1];
int G = info[2];
int U = info[3];
int D = info[4];
int[] move = { U, -D };
int[] visited = new int[F + 1];
visited[S] = 1;
Queue<int> q = new Queue<int>();
q.Enqueue(S);
while (q.Count > 0 && visited[G] == 0)
{
int now = q.Dequeue();
for (int i = 0; i < 2; i++)
{
int nxt = now + move[i];
if (nxt < 1 || nxt > F)
continue;
if (visited[nxt] != 0)
continue;
visited[nxt] = visited[now] + 1;
q.Enqueue(nxt);
}
}
if (visited[G] == 0)
Console.WriteLine("use the stairs");
else
Console.WriteLine(visited[G] - 1);
}
}
}
Comments