티스토리 뷰
// 알고리즘
1. dfs 탐색
2. 건물 층 수 만큼의 방문배열 생성 v
3. 방향 배열생성 dr {U, -D}
4. bfs 탐색 시작. 도착하면 종료
더보기
import java.util.*;
import java.io.*;
public class Main {
static int F, S, G, U, D, ans;
static boolean[] v;
static int[] dr;
static class Point {
int start, cnt, state;
public Point(int start, int cnt, int state) {
this.start = start;
this.cnt = cnt;
this.state = state;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
F = Integer.parseInt(st.nextToken()); // 전체 층
S = Integer.parseInt(st.nextToken()); // 현재 층
G = Integer.parseInt(st.nextToken()); // 도착 층
U = Integer.parseInt(st.nextToken()); // 위
D = Integer.parseInt(st.nextToken()); // 아래
ans = Integer.MAX_VALUE;
dr = new int[2];
dr[0] = U;
dr[1] = -D;
v = new boolean[F+1];
cal();
System.out.println(ans == Integer.MAX_VALUE ? "use the stairs" : ans);
}
private static void cal() {
Queue<Point> q = new LinkedList<>();
v[S] = true;
q.add(new Point(S, 0, 1));
Point p = null;
while (!q.isEmpty()) {
p = q.poll();
if (p.start == G) {
ans = p.cnt;
break;
}
for (int k = 0; k < 2; k++) {
int r = p.start + dr[k];
if (r <= 0 || r > F || v[r]) continue;
v[r] = true;
q.add(new Point(r, p.cnt + 1,0));
}
}
}
}
※ 1차원 배열의 탐색문제라서 쉽게 풀었음. 방문체크만 잘 해주면 풀 수 있는 문제인거같다.
'Algorithm' 카테고리의 다른 글
백준_네트워크 복구_2211 (0) | 2021.03.09 |
---|---|
백준_스택 수열_1874 (0) | 2021.03.07 |
백준_암호 만들기_1759 (0) | 2021.03.04 |
백준_컨베이어벨트_20055 (0) | 2021.02.27 |
백준_줄 세우기_2252 (0) | 2021.02.23 |