Question
문제 해설
- 높이가 F인 건물
- 강호는 S층에 있고, G층까지 가야함
- 한번에 엘리베이터를 이동시킬 수 있는 버튼의 개수는 2가지
- U버튼 : U의 값만큼 위로 이동
- D버튼 : D의 값만큼 아래로 이동
- G층에 도착하려면 버튼을 적어도 몇 번 눌러야 하는지
- G층 갈 수 없으면 "use the stairs"를 출력
Solution
풀이 접근 방법
- BFS 활용
- 엘리베이터가 이동할 수 있는 층의 개수를 배열에 놓고 반복문
정답 코드
public class Main_5014 {
static int F, S, G;
static int[] button;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] info = br.readLine().split(" ");
F = Integer.valueOf(info[0]);
S = Integer.valueOf(info[1]) - 1;
G = Integer.valueOf(info[2]) - 1;
button = new int[] { Integer.valueOf(info[3]), Integer.valueOf(info[4]) * -1 };
int pushCount = -1;
if (S == G) {
pushCount = 0;
} else {
pushCount = BFS();
}
bw.write(pushCount != -1 ? pushCount + " \n" : "use the stairs\n");
bw.flush();
bw.close();
}
static int BFS() {
boolean[] stairs = new boolean[F];
Queue<int[]> queue = new LinkedList<int[]>();
stairs[S] = true;
queue.add(new int[] { S, 0 });
int pushCount = -1;
while (!queue.isEmpty()) {
int[] place = queue.poll();
int stair = place[0];
int count = place[1];
for (int i = 0; i < button.length; i++) {
int newStair = stair + button[i];
int newCount = count + 1;
if (newStair < 0 || F <= newStair || stairs[newStair])
continue;
if (newStair == G) {
pushCount = newCount;
break;
}
stairs[newStair] = true;
queue.add(new int[] { newStair, newCount });
}
}
return pushCount;
}
}