Key Point

BFS를 통해 문제를 플었다. 큐를 이용해 문제를 해결하였다.
만약, U층 위, 또는 D층 아래에 해당하는 층이 없을 때는, 엘리베이터는 움직이지 않는다.
(1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000)

Explain

방문한 적이 있는지 확인할 수 있도록 dist라는 배열을 만들어서 방문하지 않았다면 -1
방문하였고, 이동했다면 1씩 증가해주었다.
dist[current]가 이전에 계산했던 이동횟수를 저장하고 있다.
F : 건물의 총 층 수
S : 강호가 위치한 층
G : 강호가 가려는 층
U : 위로 U층만큼 이동
D : 아래로 D층만큼 이동

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Exam5014 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int F = sc.nextInt(); // 건물의 층 수
int S = sc.nextInt(); // 강호가 위치해 있는 층
int G = sc.nextInt(); // 강호가 이동하려는 층
int U = sc.nextInt(); // 위로 U층만큼 이동하는 버튼
int D = sc.nextInt(); // 아래로 D층만큼 이동하는 버튼

int[] dist = new int[F+1];
Arrays.fill(dist, -1);
Queue<Integer> q = new LinkedList<Integer>();
dist[S] = 0;
q.add(S);
while(!q.isEmpty()) {
int current = q.poll();
if(current + U <=F && dist[current+U] == -1) {
q.add(current+U);
dist[current+U] = dist[current]+1;
}

if(current - D >=1 && dist[current-D] == -1) {
q.add(current-D);
dist[current-D] = dist[current]+1;
}
}
if(dist[G] == -1) {
System.out.println("Use");
}else {
System.out.println(dist[G]);
}

}

}